简体   繁体   中英

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 %}

You can try following

{% for key, item in list%}
  <option>{{ item }}</option>
{% endfor %}

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
    }
}

如果你正在使用Gulp,这可以帮助你: http//www.zell-weekeat.com/nunjucks-with-gulp#Populating-HTML-with-data

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM