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 %}
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
}
}
If you are using Gulp, this can help you: 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.