如何在树枝模板中 var_dump 变量?

发布于 2024-12-02 21:40:06 字数 443 浏览 2 评论 0原文

查看图层模式,您只显示您所获得的内容,这很好,但您如何知道哪些内容可用? TWIG 中是否有“列出所有定义的变量”功能? 有没有办法转储变量?

我通过搜索找到的解决方案是定义一个函数,我可以在其中使用我的 现有的 php 调试工具通过注入函数,但是我找到的所有参考文献包含这两行代码,但没有指定它们的放置位置。事实上,他们需要定义一个 $loader 变量,我尝试了 /app/config/autoload.php 但那里的 $loader 类型错误。 添加 twig 函数的 php 代码应该放在哪里?

View layer pattern where you only present what you have been given is fine and all, but how do you know what is available? Is there a "list all defined variables" functionality in TWIG? Is there a way to dump a variable?

The solution I found by searching for it was to define a function where I can use my existing php debug tools by injecting a function, but all references I have found to that includes these nice two lines of code, but nowhere is it specified where to place them. Going by the fact that they need a $loader variable defined, I tried /app/config/autoload.php but the $loader there was the wrong kind. Where do I place the php code for adding a twig function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

神回复 2024-12-09 21:40:06

从 Twig 1.5 开始,正确的答案是使用 dump 函数。 它在 Twig 文档中有完整记录这里是在 Symfony 中启用此功能的文档。

{{ dump(user) }}

As of Twig 1.5, the correct answer is to use the dump function. It is fully documented in the Twig documentation. Here is the documentation to enable this inside Symfony.

{{ dump(user) }}
白衬杉格子梦 2024-12-09 21:40:06

如果您所处的环境无法使用 dump 功能(例如:opencart),您可以尝试:

{{ my_variable | json_encode(constant('JSON_PRETTY_PRINT')) }}

If you are in an environment where you can't use the dump function (ex: opencart), you can try:

{{ my_variable | json_encode(constant('JSON_PRETTY_PRINT')) }}
病女 2024-12-09 21:40:06

您可以使用 debug 标签,该标签记录在此处

{% debug expression.varname %}

编辑:从 Twig 1.5 开始,此功能已被弃用并替换为新的 dump 函数(注意,它现在是一个函数,不再是一个标签)。另请参阅:上面已接受的答案。

You can use the debug tag, which is documented here.

{% debug expression.varname %}

Edit: As of Twig 1.5, this has been deprecated and replaced with the new dump function (note, it's now a function and no longer a tag). See also: The accepted answer above.

月牙弯弯 2024-12-09 21:40:06

所以我让它工作了,部分有点黑客:

  1. app/config/config.yml 中设置 twig: debug: 1
  2. 将其添加到 config_dev.yml p>

    <前><代码>服务:
    调试.twig.扩展名:
    类:Twig_Extensions_Extension_Debug
    标签:[{名称:'twig.extension'}]

  3. sudo rm -fr app/cache/dev

  4. 要使用我自己的调试函数而不是 print_r(),我打开了 vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php 并进行了更改print_r(d(

PS. 我仍然想知道如何/在哪里获取 $twig 环境来添加过滤器和扩展。

So I got it working, partly a bit hackish:

  1. Set twig: debug: 1 in app/config/config.yml
  2. Add this to config_dev.yml

    services:
        debug.twig.extension:
            class: Twig_Extensions_Extension_Debug
            tags: [{ name: 'twig.extension' }]
    
  3. sudo rm -fr app/cache/dev

  4. To use my own debug function instead of print_r(), I opened vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php and changed print_r( to d(

PS. I would still like to know how/where to grab the $twig environment to add filters and extensions.

瀟灑尐姊 2024-12-09 21:40:06

如果您在应用程序中使用 Twig 作为组件,您可以执行以下操作:

$twig = new Twig_Environment($loader, array(
    'autoescape' => false
));

$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));

然后在模板中:

{{ my_variable | var_dump }}

If you are using Twig in your application as a component you can do this:

$twig = new Twig_Environment($loader, array(
    'autoescape' => false
));

$twig->addFilter('var_dump', new Twig_Filter_Function('var_dump'));

Then in your templates:

{{ my_variable | var_dump }}
全部不再 2024-12-09 21:40:06

转储所有自定义变量:

<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
    {% if key starts with '_' %}
    {% else %}
        <pre style="background: #eee">{{ key }}</pre>
        {{ dump(value) }}
    {% endif %}
{% endfor %}

您可以使用我的插件来为您执行此操作(可以很好地格式化输出):

树枝转储栏

Dump all custom variables:

<h1>Variables passed to the view:</h1>
{% for key, value in _context %}
    {% if key starts with '_' %}
    {% else %}
        <pre style="background: #eee">{{ key }}</pre>
        {{ dump(value) }}
    {% endif %}
{% endfor %}

You can use my plugin which will do that for you (an will nicely format the output):

Twig Dump Bar

戏剧牡丹亭 2024-12-09 21:40:06

如果您使用 Twig 作为独立组件,这里有一些如何启用调试的示例,因为 dump(variable) 函数不太可能直接开箱即用

独立

运行这是在 icode4food 提供的链接上找到的

$twig = new Twig_Environment($loader, array(
    'debug' => true,
    // ...
));
$twig->addExtension(new Twig_Extension_Debug());

硅橡胶

$app->register(new \Silex\Provider\TwigServiceProvider(), array(
    'debug' => true,
    'twig.path' => __DIR__.'/views'
));

If you are using Twig as a standalone component here's some example of how to enable debugging as it's unlikely the dump(variable) function will work straight out of the box

Standalone

This was found on the link provided by icode4food

$twig = new Twig_Environment($loader, array(
    'debug' => true,
    // ...
));
$twig->addExtension(new Twig_Extension_Debug());

Silex

$app->register(new \Silex\Provider\TwigServiceProvider(), array(
    'debug' => true,
    'twig.path' => __DIR__.'/views'
));
故事与诗 2024-12-09 21:40:06

这里提供完整的配方,以便更快地参考(请注意,所有步骤都是强制性的):

1)实例化 Twig 时,传递调试选项

$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);

2)添加调试扩展

$twig->addExtension(new \Twig_Extension_Debug());

3)像 @Hazarapet Tunanyan 指出的那样使用它

{{ dump(MyVar) }}

{{ dump() }}

{{ dump(MyObject.MyPropertyName) }}

The complete recipe here for quicker reference (note that all the steps are mandatory):

1) when instantiating Twig, pass the debug option

$twig = new Twig_Environment(
$loader, ['debug'=>true, 'cache'=>false, /*other options */]
);

2) add the debug extension

$twig->addExtension(new \Twig_Extension_Debug());

3) Use it like @Hazarapet Tunanyan pointed out

{{ dump(MyVar) }}

or

{{ dump() }}

or

{{ dump(MyObject.MyPropertyName) }}
童话里做英雄 2024-12-09 21:40:06

{{ dump() }} 对我不起作用。 PHP 窒息。我猜嵌套级别太深了。

如果您使用调试器,那么您真正需要调试 Twig模板的是像这个

然后只需设置断点并在需要的地方调用 {{spect() }} 即可。您将获得与 {{ dump() }} 相同的信息,但在调试器中。

{{ dump() }} doesn't work for me. PHP chokes. Nesting level too deep I guess.

All you really need to debug Twig templates if you're using a debugger is an extension like this.

Then it's just a matter of setting a breakpoint and calling {{ inspect() }} wherever you need it. You get the same info as with {{ dump() }} but in your debugger.

何其悲哀 2024-12-09 21:40:06

由于 Symfony >= 2.6,有一个很好的 VarDumper 组件,但是Twig 的 dump() 函数不使用它。

要覆盖它,我们可以创建一个扩展:

在下面的实现中,不要忘记替换名称空间。

Fuz/AppBundle/Resources/config/services.yml

parameters:
   # ...
   app.twig.debug_extension.class: Fuz\AppBundle\Twig\Extension\DebugExtension

services:
   # ...
   app.twig.debug_extension:
       class: %app.twig.debug_extension.class%
       arguments: []
       tags:
           - { name: twig.extension }

Fuz/AppBundle/Twig/Extension/DebugExtension.php

<?php

namespace Fuz\AppBundle\Twig\Extension;

class DebugExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array (
              new \Twig_SimpleFunction('dump', array('Symfony\Component\VarDumper\VarDumper', 'dump')),
        );
    }

    public function getName()
    {
        return 'FuzAppBundle:Debug';
    }

}

Since Symfony >= 2.6, there is a nice VarDumper component, but it is not used by Twig's dump() function.

To overwrite it, we can create an extension:

In the following implementation, do not forget to replace namespaces.

Fuz/AppBundle/Resources/config/services.yml

parameters:
   # ...
   app.twig.debug_extension.class: Fuz\AppBundle\Twig\Extension\DebugExtension

services:
   # ...
   app.twig.debug_extension:
       class: %app.twig.debug_extension.class%
       arguments: []
       tags:
           - { name: twig.extension }

Fuz/AppBundle/Twig/Extension/DebugExtension.php

<?php

namespace Fuz\AppBundle\Twig\Extension;

class DebugExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array (
              new \Twig_SimpleFunction('dump', array('Symfony\Component\VarDumper\VarDumper', 'dump')),
        );
    }

    public function getName()
    {
        return 'FuzAppBundle:Debug';
    }

}
挽你眉间 2024-12-09 21:40:06

要调试 Twig 模板,您可以使用调试语句

在此处输入图像描述

您可以在此处明确设置调试设置。

For debugging Twig templates you can use the debug statement.

enter image description here

There you can set the debug setting explicitely.

听闻余生 2024-12-09 21:40:06

您可以编辑

/vendor/twig/twig/lib/Twig/Extension/Debug.php

var_dump() 函数并将其更改为 \Doctrine\Common\Util\Debug::dump()

You can edit

/vendor/twig/twig/lib/Twig/Extension/Debug.php

and change the var_dump() functions to \Doctrine\Common\Util\Debug::dump()

紫罗兰の梦幻 2024-12-09 21:40:06

由于大多数优秀的 PHP 程序员都喜欢使用 XDebug 来实际单步执行正在运行的代码并实时观察变量的变化,因此使用 dump() 感觉就像回到了过去的糟糕日子。

这就是为什么我做了一个 Twig Debug 扩展并将其放在 Github 上。

https://github.com/delboy1978uk/twig-debug

作曲家需要 delboy1978uk/ twig-debug

然后添加扩展。如果您不使用 Symfony,如下所示:

<?php

use Del\Twig\DebugExtension;

/** @var $twig Twig_Environment */
$twig->addExtension(new DebugExtension());

如果您使用 Symfony,则在服务 YAML 配置中如下所示:

twig_debugger:
    class: Del\Twig\DebugExtension
    tags:
        - { name: twig.extension }

注册后,您现在可以在 twig 模板中的任何位置执行此操作:

{{ breakpoint() }}

现在,您可以使用 XDebug,执行将暂停,然后您可以看到上下文和环境的所有属性。

玩得开心! :-D

As most good PHP programmers like to use XDebug to actually step through running code and watch variables change in real-time, using dump() feels like a step back to the bad old days.

That's why I made a Twig Debug extension and put it on Github.

https://github.com/delboy1978uk/twig-debug

composer require delboy1978uk/twig-debug

Then add the extension. If you aren't using Symfony, like this:

<?php

use Del\Twig\DebugExtension;

/** @var $twig Twig_Environment */
$twig->addExtension(new DebugExtension());

If you are, like this in your services YAML config:

twig_debugger:
    class: Del\Twig\DebugExtension
    tags:
        - { name: twig.extension }

Once registered, you can now do this anywhere in a twig template:

{{ breakpoint() }}

Now, you can use XDebug, execution will pause, and you can see all the properties of both the Context and the Environment.

Have fun! :-D

蓝眼泪 2024-12-09 21:40:06

您可以使用 dump 函数并像这样打印它,

{{ dump(MyVar) }}

但也有一件好事,如果您没有为 dump 函数设置任何参数,它将打印 所有变量都可用,像

{{ dump() }}

you can use dump function and print it like this

{{ dump(MyVar) }}

but there is one nice thing too, if you don't set any argument to dump function, it will print all variables are available, like

{{ dump() }}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文