0

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.

2 Answers 2

1

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);
1
  • Thank you! that does the job!
    – Chsir17
    Jun 4, 2018 at 18:35
0

Alternatively, without additional rendering, if circumstances permit:

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.