Skip to content

Recursivity in dictionnaries doesn't work #2046

@njaros

Description

@njaros

Hello there :)
I want to template a .rst file for any json structure using the jinja recursive feature

It works well for lists, but I'm stuck trying to make it works with dictionnaries

Here is my template to easily reproduce the bug :

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

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

  {%- else %}

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

{%endfor%}

They're is a little Python script to provide a little dict structure :

    path = Path(__file__).parent

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

    rendered = template.render(sample={"a": {"b": "c"}})
    with open(path.joinpath("source/sphinx_sample.rst"), "w") as io:
        io.write(rendered)

The execution of the script brings me the following error :

File "/home/jaja/Bureau/coding/bac_a_sable/sphinx_test/templates/template1.rst", line 5, in top-level template code
    {% for k, v in sample.items() recursive %}
    ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/jaja/Bureau/coding/bac_a_sable/sphinx_test/templates/template1.rst", line 13, in template
    {{ loop(v) }}
^^^^^^^^^^^^^^^^^^
  File "/home/jaja/Bureau/coding/bac_a_sable/sphinx_test/templates/template1.rst", line 5, in template
    {% for k, v in sample.items() recursive %}
    ^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 2, got 1)

I expect to have a file containing the dict like:

  • a
  • b
  • c

Environment:

  • Python version: 3.11.2
  • Jinja version: 3.1.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions