Here is a debuging macro to view easy to read `__tera_context`

I created a short script that displays the same stuff as {{ __tera_context }}, but each variable is in it’s own accordion <details> element. It also put page content and sub-pages in their own <details>. It’s easier to quickly view if you have messed something up or forget the structure of something. Extremely useful for neophytes just starting to learn Tera.

Any suggestions to make it better are welcome. It shows the contents of the __tera_context_ string by individually shows the contest of config, section or page, current_path, current_url, lang. I’d rather the last 3 be combined in one drop-down, but I believe we cannot create arrays or objects with Tera.


{% macro show_tera_context() %}
    {{ self::show(name="Config", content=config) }}
    {% if section %}{{ self::show(name="Section", content=section) }}{% endif %}
    {% if page %}{{ self::show(name="Page", content=page) }}{% endif %}
    {{ self::show(name="current_path", content=current_path) }}
    {{ self::show(name="current_url", content=current_url) }}
    {{ self::show(name="lang", content=lang) }}
{% endmacro show_tera_context %}


{% macro show(name, content) %}
    <details style="text-align: left;">
        <summary><strong>{{ name }}</strong></summary>
        {{ self::show_value(type="",data=content) }}
    </details>
{% endmacro show %}


{% macro show_array(data) %}
    <ul>
    {% for value in data %}
        <li><strong>{{ loop.index }}</strong>: {{ self::show_value(type="",data=value) }}</li>
    {% endfor %}
    </ul>
{% endmacro show_array %}


{% macro show_object(data) %}
    <ul>
    {% for key,value in data %}
        <li><strong>{{ key }}</strong>: {{ self::show_value(type=key,data=value) }}</li>
    {% endfor %}
    </ul>
{% endmacro show_object %}


{% macro show_value(type, data) %}
    {% if type == "pages" %}
        {% for page in data %}
            {{ self::show(name=page['title'], content=data) }}
        {% endfor %}
    {% elif type == "content" %}
        {{ self::show(name=type, content=data) }}
    {% elif data is object %}
        {{ self::show_object(data=data) }}
    {% elif data is iterable %}
        {{ self::show_array(data=data) }}
    {% else %}
        {{ data }}
    {% endif %}
{% endmacro show_value %}

I drop that in to templates/macros/debug.html and in my base.html theme or template file add to the top:

{% import "macros/debug.html" as debug %}

and add in the footer for the site:

{{ debug::show_tera_context() }} 

And you can leave it there during main development if you keep making some basic mistakes.

4 Likes