Scroll through an object in nunjucks?

I have a file called "list.json" configured as follows:

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

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

 {% for item in list%} <option>{{ thing }}</option> {% endfor %} 
+5
source share
4 answers

You can try to run

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

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

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

If you use it several times, add a variable at the top of the file instead.

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

You can also use the asynchronous method, but you need some attachment:

 fs.readFile('list.json', function(err, list) { env.render('template.html', { list: list, //other data } } 
+1
source

First you must create an array of objects at the end:

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

Now at the front end you can skip this array, as shown below:

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

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1241032/


All Articles