Chsir17
Chsir17

Reputation: 757

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.

Upvotes: 0

Views: 1670

Answers (2)

aradul
aradul

Reputation: 1

Alternatively, without additional rendering, if circumstances permit:

dict = {
    name: 'John',
    lastname: 'Smith'
}

dict = {
    greeting: 'Hello, my name is ' + dict.name + ' ' + dict.lastname
}

Upvotes: 0

Aikon Mogwai
Aikon Mogwai

Reputation: 5225

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

Upvotes: 1

Related Questions