IT박스

나뭇 가지 템플릿에서 변수를 var_dump하는 방법은 무엇입니까?

itboxs 2020. 6. 7. 10:51
반응형

나뭇 가지 템플릿에서 변수를 var_dump하는 방법은 무엇입니까?


주어진 내용 만 제시하는보기 레이어 패턴은 훌륭하지만 모든 것이 가능한지 어떻게 알 수 있습니까? TWIG에 "모든 정의 된 변수 나열"기능이 있습니까? 변수를 덤프하는 방법이 있습니까?

내가 찾은 해결책은 function 주입하여 기존의 PHP 디버그 도구사용할 수있는 함수를 정의하는 것이었지만, 내가 찾은 모든 참조에는이 멋진 두 줄의 코드가 포함되어 있지만 어디에 어디에도 지정되어 있지 않습니다. 그들을 배치하십시오. $ loader 변수가 정의 되어 있다는 사실에 따라 /app/config/autoload.php를 시도했지만 $ loader에 잘못된 종류가 있습니다. 나뭇 가지 함수를 추가하기 위해 PHP 코드를 어디에 배치합니까?


Twig 1.5부터 정답은 덤프 기능을 사용하는 것입니다. Twig 문서에 완전히 문서화되어 있습니다 . 다음은 Symfony2에서이를 활성화하기위한 설명서입니다.

{{ dump(user) }}

여기debug 에 설명 된 태그 를 사용할 수 있습니다 .

{% debug expression.varname %}

편집 : Twig 1.5 dump부터는 더 이상 사용되지 않으며 새로운 기능으로 대체되었습니다 (이제 기능이며 더 이상 태그가 아닙니다). 위의 답변을 참조하십시오.


그래서 부분적으로 약간 hackish가 작동했습니다.

  1. 설정 twig: debug: 1에서app/config/config.yml
  2. 이것을 config_dev.yml에 추가하십시오

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

  4. 대신 내 자신의 디버그 기능을 사용하려면 print_r(), 내가 개설 vendor/twig-extensions/lib/Twig/Extensions/Node/Debug.php및 변경 print_r(d(

추신. 필터와 확장을 추가하기 위해 $ twig 환경을 얻는 방법 / 위치를 알고 싶습니다.


응용 프로그램에서 Twig를 구성 요소 로 사용하는 경우 다음을 수행 할 수 있습니다.

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

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

그런 다음 템플릿에서 :

{{ my_variable | var_dump }}

Twig를 독립 실행 형 구성 요소로 사용하는 경우 덤프 (변수) 기능이 즉시 작동 하지 않을 수 있으므로 디버깅을 활성화하는 방법에 대한 몇 가지 예가 있습니다.

독립형

이것은 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'
));

모든 사용자 정의 변수를 덤프하십시오.

<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() }}나를 위해 작동하지 않습니다. PHP질식. 중첩 수준이 너무 깊습니다.

debug사용하는 경우 템플릿 을 실제로 수정 해야하는 debugger것은 이와 같은 확장 입니다.

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.


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';
    }

}

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) }}

For debugging Twig templates you can use the debug statement.

enter image description here

There you can set the debug setting explicitely.


You can edit

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

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


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


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() }}

참고URL : https://stackoverflow.com/questions/7317438/how-to-var-dump-variables-in-twig-templates

반응형