[Answer]-Iterating over nested list

1πŸ‘

βœ…

{{ for x in ... }} is causing a TemplateSyntaxError and should be {% for x in ... %}.

python manage.py shell

from django.template import Template, Context

data_list = [[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3, 4, 5]]]
template = """
    {% for obj in data_list %}
        Obj {{obj.0}}
        {% for nested_obj in obj.1 %}
            Nested {{nested_obj}}
        {% endfor %}
    {% endfor %}
    """

t = Template(template)
c = Context({"data_list": data_list})

print t.render(c)

Out:

    Obj 1

        Nested 1

        Nested 2

        Nested 3


    Obj 2

        Nested 2

        Nested 3

        Nested 4


    Obj 3

        Nested 3

        Nested 4

        Nested 5
πŸ‘€allcaps

0πŸ‘

Maybe this is working…

data_list = [[1, [1, 2, 3]], [2, [2, 3, 4]], [3, [3,4,5]]]

{% for header, remainder in data_list %}
    <h2>a</h2>
    <p>
    {{ for x in remainder }}
        <h5>{{ x }}</h5>
    {{ endfor }}
    </p>
{% endfor %}
πŸ‘€Mihai Zamfir

Leave a comment