user1037355
user1037355

Reputation:

Nunjucks import template and pass in specific data like the twig "with" keyword

https://mozilla.github.io/nunjucks/templating.html#include

I want to be able to pass data to the included template.

Nunjucks is very very similar to Twig and of course is based on Ninja..

In twig one can import a tpl and pass in data: https://twig.symfony.com/doc/2.x/tags/include.html

I really need to be able to do this in a nodejs project with nunjucks, is it possible?

Upvotes: 1

Views: 3073

Answers (1)

Aikon Mogwai
Aikon Mogwai

Reputation: 5225

The simplest way is to define custom filter render. It accepts a template name as filtered value and data as arguments: {{ 'some-template-name' | render(data) }}.

/views
  test.html
  test2.html
app.js

//app.js
const nunjucks = require('nunjucks');
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader('views'));

env.addFilter('render', function (template, ctx) {
    try {
        return env.filters.safe(env.render(template, ctx));
    } catch (err) {
        return err.message;
    }
});

var html =  env.render('test.html', {a: '100'});
console.log(html);

// test.html
TEST {{a}}
{{ 'test2.html' | render({b: 200}) }}   

// test2.html
TEST2 {{b}}

Also you could define own tags (extension) e.g. {% mytag = "/some-template-path", {data} %}

P.S. Async version

env.addFilter('render', function (template, ctx, cb) {
    try {
        env.render(template, ctx, (err, html) => cb(err, !err ? env.filters.safe(html) : undefined))
    } catch (err) {
        console.error('Render error', err.message);
        console.error(template, ctx);
        cb(err);
    }
}, true);

Upvotes: 1

Related Questions