7

I have a file called "list.json" set up like this:

{
  "thing1": "Thing1",
  "thing2": "Thing2",
  "thing3": "Thing3"
}

How can I loop through this? I want to do something like:

{% for item in list%}
  <option>{{ thing }}</option>
{% endfor %}
j_d
  • 2,818
  • 9
  • 50
  • 91
  • Possible duplicate of [Loop through object properties nunjucks](https://stackoverflow.com/questions/20990516/loop-through-object-properties-nunjucks) – KyleMit Sep 02 '19 at 17:31

4 Answers4

7

You can try following

{% for key, item in list%}
  <option>{{ item }}</option>
{% endfor %}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Have you imported the JSON? If not, in the render JS, add a variable:

list: JSON.parse(fs.readFileSync('list.json'))

If you are using it multiple times, add a variable at the top of the file instead.

var LIST = JSON.parse(fs.readFileSync('list.json'))

It's also possible to use the asynchronous method, but you need some nesting:

fs.readFile('list.json', function(err, list) {
    env.render('template.html', {
        list: list,
        //other data
    }
}
somebody
  • 478
  • 10
  • 17
0

If you are using Gulp, this can help you: http://www.zell-weekeat.com/nunjucks-with-gulp#Populating-HTML-with-data

Emanuel Saramago
  • 462
  • 4
  • 16
0

You should first create an array of objects in back end :

var things = [];

things.push({id : 'thing1', name : 'Thing1'});
things.push({id : 'thing2', name : 'Thing2'});
things.push({id : 'thing3', name : 'Thing3'});

Now on front end you would be able to loop through this array like below :

{% for thing in things %}
<option value="{{ thing.id }}"> {{ thing.name }}</option>
{% endfor %}

I hope this will help you out.

Ankit
  • 627
  • 1
  • 9
  • 22