Nunjucks nested variables

时间:2018-06-04 17:27:05

标签: html sql web jinja2 nunjucks

Are nested variables possible in Nunjucks? I need to be able to store a string in my database containing Nunjucks variable but it does not seem to work. Here's an example of what I need to be able to do:

dict = {
name: 'John',
lastname: 'Smith',
greeting: 'Hello, my name is {{ name }} {{ lastname }}'
}

And then be able to do

<span>{{greeting}}</span>

but it outputs this:

'Hello, my name is {{ name }} {{ lastname }}'

The reason i need it this way it because I have a database with some description templates with holes and i have a database with values and I need to be able to combine them. But it is not always the same values so I cant hard-code them.

1 个答案:

答案 0 :(得分:0)

最简单的方法是添加globalfilter

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

env.addFilter('render', function(text) {
    return  nunjucks.renderString(text, this.ctx);
});

var res = nunjucks.renderString(
    'name: {{name}}, greeting: {{greeting | render}}', 
    {
        name: 'John',
        greeting: 'Hello {{name}}'
    }
);

console.log(res);