Sorry if I report with a problem that has been dealt with frequently in the forum. I get the error message that the template was not found.
Error: template not found: D:\Development\src\nunjucks\pages\templates\text.njk
What am I doing wrong with the directory structure specification? Is there a way how to generate html files from nunjucks files like gulp? With gulp it works.
This is the script for node.js:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const nunjucks = require('nunjucks');
app.use(express.static('dist'));
nunjucks.configure('src/nunjucks', {
autoescape: true,
express: app,
watch: true
});
app.engine ('njk', nunjucks.render);
app.set('view engine', 'njk');
app.get('/', (req, res) => {
res.render('pages/index2');
console.log("index");
})
server.listen(3010, () => {
console.log('http://localhost:' + 3010);
})
And this is the directory structure:
app.js
gulpfile.js
|-src
| |-nunjucks
| |-pages
| | index.njk
| |-templates
| text.njk
And this is the index.njk file:
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<h1>Header Test</h1>
{% include "text.njk" %}
</body>
</html>
All your templates will be resolved from the path(s) you a passing to nunjucks.configure
.
In your case you should include template with path from src/nunjucks
.
Eg templates/text.njk
.
That is the solution in the script for node.js
nunjucks.configure('src/nunjucks', {
autoescape: true,
express: app,
cache: false,
watch: true
});
// app.set('views', 'src/nunjucks/pages');
app.engine ('njk', nunjucks.render);
app.set('view engine', 'njk');
app.get('/', (req, res) => {
res.render('pages/index.njk');
})
app.get('/index.html', (req, res) => {
res.render('pages/index.njk');
})
And the index.html file
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
</head>
<body>
<h1>Header Test</h1>
{% include "../templates/text.njk" %}
</body>
</html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.