Jinja2 and Json Jinja2 and Json json json

Jinja2 and Json


The documentation reads:

It is possible to use loops recursively. This is useful if you are dealing with recursive data such as sitemaps. To use loops recursively you basically have to add the recursive modifier to the loop definition and call the loop variable with the new iterable where you want to recurse.

In your case this would be accomplished with the following:

<ul>{% for key, value in linksList.items() recursive %}    <li>    {% if value is string %}        <a href="{{ value }}">{{ key }}</a>    {% else %}        {{ key }}        <ul>{{ loop(value.items()) }}</ul>    {% endif %}    </li>{% endfor %}</ul>


My 2 cents, just if someone comes here looking for rendering a JSON using Jinja, and complementing the response from @Ryon Sherman :)

  1. Since JSON may have int values as well as strings, you can use if value is mapping (and flip the if-condition)
  2. If your output must feel like a JSON you can use {{key|indent(width)}} + loop.depth
  3. In my case, the template was for an email and key|indent() didn't work as expected so I ended up using an auxiliar {% for %} loop:
<div>    <code>{    {% for key, value in dic.items() recursive %}    {% if value is mapping %}    <p>     {% for it in range(loop.depth) %}  {% endfor %}{{key}}: {    </p>    {{ loop(value.items()) }}    <p>      {% for it in range(loop.depth) %}  {% endfor %}}    </p>    {% else %}    <p>      {% for it in range(loop.depth) %}  {% endfor %}{{key}}: {{value}},    </p>    {% endif %}    {% endfor %}    }</code></div>