簡體   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