Nunjucks
There are many template engines for node.js, but nunjucks can be written in python. See here for detailed documentation. https://mozilla.github.io/nunjucks/
Almost the same as Jinja2. http://jinja.pocoo.org/docs/dev/
$ npm install nunjucks --save
app.js
var express = require('express');
var path = require('path');
var nunjucks = require('nunjucks');
var app = express();
// nunjucks view engine
nunjucks.configure('views', {
autoescape: true,
express: app
});
// setup view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
If you are using ʻexpress, specify it in
nunjucks.configure.
view engine is now
html`.
{% set x = 5 %}
{{ x }}
{% if variable %}
It is true
{% endif %}
{% set items = [{"title": "a"}, {"title": "b"}] %}
{% for item in items %}
<p>{{ item.title }}</p>
{% endfor %}
Try using a library called nunjucks-date-filter. It seems that moment is used as a template.
$ npm install nunjucks-date-filter --save
$ npm install consolidate --save
app.js
var express = require('express');
var path = require('path');
var nunjucks = require('nunjucks');
var dateFilter = require('nunjucks-date-filter');
var cons = require('consolidate');
var app = express();
// nunjucks view engine
cons.requires.nunjucks = require('nunjucks');
var env = cons.requires.nunjucks.configure('views', {
autoescape: true,
express: app
});
// date format
dateFilter.setDefaultFormat('YYYY-MM-DD');
env.addFilter('date', dateFilter);
// setup view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
// with no format
This blog has been created at {{ creation_date | date }}.
// with a custom format
This blog has been created at {{ creation_date | date("YYYY") }}.
// with an addition first
This blog has been created at {{ creation_date | date("add", 7, "days") | date }}.
Recommended Posts