How to get all twig variables from template

Written on 2020-03-11 23:59:00

Last updated 2020-03-11 23:59:00

This is how I use to debug any twig template and it's variables. Just include into your twig template and pass variable = object | array | null

{% partial 'debug' variable=post %}
{% if this.environment != ('production' or 'prod' ) %}
    <ol>
        {% if variable is defined %}
            {% set debugItem = variable %}
        {% else %}
            {% set debugItem = _context %}
        {% endif %}

        {% if debugItem is iterable %}
            {% for key, values in debugItem  %}
            <li><b>{ { key } }</b></li>
            <ol>
                {% if values is iterable %}
                {% for k, v in values  %}
                <li>{ { k } }</li>
                {% endfor %}
                {% else %}
                {# values is probably a string or json #}
                <pre class=" language-json">
                    <code class=" language-bash">
                           { { values|json_encode(constant('JSON_PRETTY_PRINT')) } }
                        </code>
                </pre>
                {% endif %}
            </ol>
            {% endfor %}
        {% else %}
        <pre class=" language-json">
                    <code class=" language-bash">
                           { { debugItem|json_encode(constant('JSON_PRETTY_PRINT')) } }
                        </code>
                </pre>
        {% endif %}
    </ol>
{% endif %}
blog comments powered by Disqus