I have successfully integrated nunjucks templating into my express app. Below is the directory structure of my project:
. nunjucks-project
|__ api
|__ node_modules
|__ views
|__ templates
|__ layouts
|__ default.html
|__ pages
|__ home.html
|__ partials
|__ header.html
|__ footer.html
Take a look at my app.js :
/**
* Author Kailash K Yogeshwar 2016
*/
var express = require('express');
var nunjucks = require('nunjucks');
var mongoose = require('mongoose');
var path = require('path');
var config = require('config');
var app = express();
var viewRoutes = require("./routes/viewroutes/index");
var apiRoutes = require("./routes/apiroutes/index");
var dbUrl = "mongodb://localhost:27017/techblogs";
mongoose.connect(dbUrl);
mongoose.connection.on('open',() => {
console.log("Connection successfully established")
});
mongoose.connection.on("error",(err) => {
console.error(err);
});
//configure views
app.set('views', path.join(__dirname, "views", "templates"));
app.set('view engine', 'html');
// configure nunjucks
var env = nunjucks.configure(app.get('views'), {
autoescape: true,
dev: true,
noCache: true,
throwOnUndefined: true,
express : app
});
console.log(JSON.stringify(env, null, 3))
app.use('/', viewRoutes);
app.use('/api', apiRoutes);
app.listen(process.env.PORT || 8080, () => {
console.log("Server Started to listen on ",process.env.PORT || 8080);
});
module.exports = app;
Now, let's dive into default.html and home.html :
!<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{% include 'partials/header.html' %}
{% block content %} {% endblock %}
{% include 'partials/footer.html' %}
</body>
</html>
home.html
{% extends "layouts/default.html" %}
{% block content %}
<h1> I am home page <h1>
{% endblock %}
I have noticed that the "extends" function only works if the template is in the same directory, and not in a separate directory. I also attempted to specify multiple paths in nunjucks.configure([paths],{}) but it only takes the first path into account, considering the rest as relative paths.
Here is a screenshot for reference: