htmlsqlwebjinja2nunjucks

Nunjucks nested variables


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.


Solution

  • The simplest way is a add global or filter

    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);