繁体   English   中英

nunjucks:错误:找不到模板,目录问题

[英]nunjucks: Error: template not found, Problems with directories

抱歉,如果我报告了论坛中经常处理的问题。 我收到找不到模板的错误消息。

错误:找不到模板:D:\Development\src\nunjucks\pages\templates\text.njk

我对目录结构规范做错了什么? 有没有办法从像 gulp 这样的 nunjucks 文件生成 html 文件? 使用 gulp 它可以工作。

这是 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);
})

这是目录结构:

app.js
gulpfile.js
|-src
|  |-nunjucks
|    |-pages
|    |    index.njk
|    |-templates
|         text.njk

这是 index.njk 文件:

<html lang="en">
<head>
  <title>Test</title>
  <meta charset="utf-8">
</head>
<body>
  <h1>Header Test</h1>
  {% include "text.njk" %}
</body>
</html>

您的所有模板都将从您传递给nunjucks.configure的路径中解析。

在您的情况下,您应该包含带有src/nunjucks路径的模板。

例如templates/text.njk

这是 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');
})

以及索引.html文件

<html lang="en">
<head>
    <title>Test</title>
    <meta charset="utf-8">
</head>
<body>
    <h1>Header Test</h1>
    {% include "../templates/text.njk" %}
</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM