Nunjucks
How to install and use Nunjucks
The installation is easy, which follows the installation of all other packages.
npm install nunjucks
Then, you can use nunjucks below:
const nunjucks=require('nunjucks');
nunjucks.configure('views', { autoescape: true });
nunjucks.renderString('Hello {{ username }}', { username: 'Cao' });
Nunjucks can be used together with express like below:
const nunjucks=require('nunjucks');
var app = express();
nunjucks.configure('views', {
autoescape: true,
express: app
});
app.get('/', function(req, res) {
res.render('index.njk');
});
Note that you need to turn on autoescape
to ensure security.
Templating
- Variable
{{ username }}
- Filters
{{ foo | replace("*", "#") | capitalize }}
- Inheritance
First, you can define the following parent.njk.
{% block c %}
Top
{% endblock %}
<section class="style1">
{% block a %}
{% endblock %}
</section>
<section class="style2">
{% block b %}
{% endblock %}
</section>
Then, you can inherit from the parent and redefine blocks.
{% extends "parent.njk" %}
{% block a %}
This is Block a!
{% endblock %}
{% block b %}
This is Block b!
{% endblock %}
The output will be as follows:
Top
<section class="style1">
This is Block a!
</section>
<section class="style2">
This is Block b!
</section>
More details can be found at this document.