I want to render any njk file with express nunjucks Examples I found online contain only:
app.get('/', function (req, res) {
res.render('index.njk');
});
But how to implement this? Thank you
const express = require('express');
const nunjucks = require('nunjucks');
/*
options and other code is here
*/
// index.njk, contacts.njk, ..., anything.njk
app.get('any *.njk file', function (req, res) {
if('any *.njk file exists' == true) {
res.render('any *.njk file');
} else {
console.log('error 404');
res.render('404.njk');
}
});
update:
What I have now is:
app.get(/^\/. \.njk$/, function (req, res) {
let file = req.url.replace(/\//, '');
// if(fileExists == true)
res.render(file);
});
Easiest way to get file from request:
app.get("/:templateName", function (req, res) {
res.render(req.params.templateName);
});
CodePudding user response:
You can do this with route parameters.
For example:
app.get("/:templateName", function (req, res) {
// Check if the file exists, render it etc.
console.log(req.params.templateName);
});