Referenced Original Github Referenced Nunjucks and Express App Tutorial
npx express-generator myapp --no-view
// or
npx express-generator . --no-view
// then
npm i express dotenv nunjucks
// mkdir
mkdir views && touch views/layout.njk && touch views/index.njk
// We are going to specify nunjucks as the view engine
// So get rid of the placeholder `index.html` in /public.
mv public/index.html old-index.html
// At `app.js` configute Nunjucks with 'views' as templates directory
let nunjucks = require("nunjucks");
nunjucks.configure("views", {
autoescape: true,
express: app,
});
// Render `index.njk` when someone visits home; edit `/routes/index.js`
let express = require("express");
let router = express.Router();
router.get("/", async function (req, res, next) {
let data = {
title: "Nunjucks example",
layout: "layout.njk",
message: "Hello world!",
};
res.render("index.njk", data);
});
module.exports = router;
// Start app
yarn start
// open in browser
http://localhost:3000/
We are feeding
layout.njk
template intoindex.njk
Configured inside
routes/index.js
we are passingdata = {layout: "layout.njk"}
intores.render("index.njk", data);