Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested Nunjucks For Loop

I am trying to write a nunjucks template that loops through an outer array and populates columns, then loops through a nested array to make rows in each column.

So, my data structure looks something like this:

var data = [
    {
        'type' : 'fruit',
        'list' : ['banana', 'kiwi', 'strawberry']
    },
    {
        'type' : 'vegetables'
        'list' : ['tomato', 'carrot', 'zucchini']
    }
]

I want to create an html doc that looks like this:

<div>
    <span>fruit</span>
    <ul>
         <li>banana</li>
         <li>kiwi</li>
         <li>strawberry</li>
    </ul>
</div>

<div>
    <span>vegetables</span>
    <ul>
         <li>tomato</li>
         <li>carrot</li>
         <li>zucchini</li>
    </ul>
</div>

I have tried making a nunjucks template that looks something like this:

{% for category in data %}
    <div>
        <span>{{category.type}}</span>
        <ul>
           {% for thing in category.list %}
            <li>{{thing}}</li>
           {% endfor %}
        </ul>
    </div>
{% endfor %}

But, for some reason, I can't access the inner variables. I don't really have access to the inner for loop. I have looked on stack overflow, and through their documentation, but can't find anything about nested for loops.

Any help would be greatly appreciated. Thank you.

like image 325
justinbc820 Avatar asked Mar 13 '15 22:03

justinbc820


1 Answers

Missing colon in json might cause the issue...

So instead of this

'type' : 'vegetables'

try this

'type' : 'vegetables',
like image 104
Mamba Avatar answered Sep 17 '22 12:09

Mamba