簡體   English   中英

nunjucks:找不到模板

[英]nunjucks: Template not found

試圖渲染一個 nunjucks 模板但得到Error: template not found: email.html

server/
  views/
     email/
       email.html
  workers/
      email.worker.js
//email.worker.js
function createMessage(articles) {
   console.log(__dirname) // /<path>/server/workers

   nunjucks.configure('../views/email/');
   return nunjucks.render('email.html', articles);
}

不知道這里有什么問題。

我遇到了同樣的問題,我的解決方案是使用路徑模塊:

const njk = require('nunjucks');

return njk.render(path.resolve(__dirname, '../views/email/' + 'email' + '.html'), articles);

我有同樣的問題。 我在文檔中找到了這個:

在節點中,“視圖”將是相對於當前工作目錄的路徑。

如果您在根目錄運行節點服務器,則模板路徑將為server/views

 nunjucks.configure('server/views/email/');
 return nunjucks.render('email.html', articles);

就我而言,服務器腳本位於public目錄中。

在此處輸入圖像描述

因此,當我從根目錄運行服務器時,nunjucks 配置將如下所示:

 nunjucks.configure('src/templates');
 return nunjucks.render('index.html', { name : 'Dian' });

有用。

但是如果我從public目錄運行服務器,則找不到模板。

遇到同樣的問題,如果有幫助,試試這個。 如果您使用的是 express 並且有一個views文件夾:

來自nunjucks文檔

var app = express();

nunjucks.configure('views', {
    autoescape: true,
    express: app
});

您可以使用 nodejs 的__dirname為您解析路徑

nunjucks.configure(__dirname + '/views')...

在我的例子中,nunjucks 模板(位於 src 下)不包含在 build 文件夾中。 我的nest-cli.json 文件中的這樣一個配置解決了我的問題:

{
  "$schema": "https://json.schemastore.org/nest-cli",
  "collection": "@nestjs/schematics",
  "sourceRoot": "src",
  "compilerOptions": {
    "assets": [
      "**/*.njk"
    ]
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM