Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through object in nunjucks?

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 %}
like image 725
j_d Avatar asked Jan 20 '16 14:01

j_d


2 Answers

You can try following

{% for key, item in list%}
  <option>{{ item }}</option>
{% endfor %}
like image 152
Nikhil Aggarwal Avatar answered Nov 18 '22 15:11

Nikhil Aggarwal


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
    }
}
like image 1
somebody Avatar answered Nov 18 '22 15:11

somebody