Skip to content

Recursivity in dictionnaries doesn't work #2047

Answered by JamesParrott
njaros asked this question in Q&A
Discussion options

You must be logged in to vote

Jaja, recursivity with dictionaries works great. The bug is in your example template.

You just need to use loop(v.items()) instead of loop(v)

template1.rst

{% for k, v in sample.items() recursive %}
  - {{ k }}

  {%- if v is string %}
    - {{ v }}

  {%- else %}

    {{ loop(v.items()) }}
  
  {%- endif -%}

{%endfor%}

jinja2_recursive.py


from pathlib import Path
from jinja2 import Environment, FileSystemLoader

path = Path(__file__).parent

env = Environment(
    loader=FileSystemLoader(path)
)
template = env.get_template("template1.rst")

rendered = template.render(sample={"a": {"b": "c"}})
print(rendered)
>python jinja2_recursive.py

  - a


  - b
    - c

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@JamesParrott
Comment options

@njaros
Comment options

Answer selected by njaros
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #2046 on November 09, 2024 15:28.