【问题标题】:nunjucks: Template not foundnunjucks:找不到模板
【发布时间】:2016-08-20 05:29:22
【问题描述】:

试图渲染一个 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);
}

不知道这里出了什么问题。

【问题讨论】:

  • 仅供参考,我还尝试配置不带斜杠的路径。
  • 我使用path 模块来获取模板目录的绝对路径并让它工作。提供相对路径不起作用。
  • 试试nunjucks.configure('views/email/')

标签: node.js nunjucks


【解决方案1】:

遇到同样的问题,如果有帮助,试试这个。如果您使用的是 express 并且您有一个 views 文件夹:

来自nunjucks docs

var app = express();

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

您可以使用nodejs的__dirname为您解析路径

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

【讨论】:

    【解决方案2】:

    我的解决方案使用路径模块时遇到了同样的问题:

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

    【讨论】:

      【解决方案3】:

      我有同样的问题。我在documentation 找到了这个:

      在节点中,'views' 是相对于当前工作目录的路径。

      如果在根目录运行节点服务器,则模板路径为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 目录运行服务器,则找不到模板。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多