简体   繁体   中英

building a array/object in a nunjucks loops

I have the following in my nunjucks file,

{% set inProgressJobs = [] %}
{% for job in jobs %}
 {% set inProgressJobs = (setProgressJobs.push([
    {
         text: "<b><a href="">{{ job.jobTitle}}</a></b>"
    }
 ]), inProgressJobs) %}

When I use this in by view I would expect to see Web Designer but I am actually seeing {{ job.jobTitle }} how I interprolate my var into the text attribute?

You try to coding inside a template. It's a possible (see below) but out of template ideology. Try to put necessary logic to filters and global functions.

const nunjucks  = require('nunjucks');
const env = nunjucks.configure();

env.addFilter('print', console.log); // for debug

const html = env.renderString(`
    {% set arr = [] %}
    {% for i in range(1, 10) %}
        {{ '' if arr.push(i) }} {# arr.push always returns non-zero so result will be '' #}
    {% endfor %}
    {{ arr | print }} {# print arr to console #}
`);
// console.log(html); // html is a pack of spaces and tabs 

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