簡體   English   中英

如何引用節點模塊中包含的 nunjucks 模板?

[英]How to reference a nunjucks template included in a node module?

如果我想 package 一個帶有節點模塊的 nunjucks 模板文件,我如何引用打包的模板文件,以便在全局安裝 package 時普遍可用?

我有以下節點文件index.js

#!/usr/bin/env node

var nunjucks = require('nunjucks');

var env = nunjucks.configure('./');
var template = env.getTemplate('template.html');
var output = template.render({
  h1_copy: "Foo and Bar"
});

console.log(output);

這是模板.html:

<html>
  <body>
    <h1>{{ h1_copy }}</h1>
  </body>
</html>

我將它設置為在 package.json 中有一個二進制命令:

"bin": {
  "make_output": "./index.js"
}

現在,如果我全局安裝它,我可以運行make_output來制作 output:

node-nunjucks$ npm install -g .
/usr/local/bin/make_output -> /usr/local/lib/node_modules/node-nunjucks/index.js
+ node-nunjucks@1.0.0
added 1 package in 0.099s

node-nunjucks$ make_output
<html>
  <body>
    <h1>Foo and Bar</h1>
  </body>
</html>

但這僅在我運行命令的目錄中存在template.html時才有效。 如果我嘗試從其他任何地方運行全局命令,它將找不到模板:

node-nunjucks$ cd ..
tmp$ make_output
/private/tmp/node-nunjucks/node_modules/nunjucks/src/environment.js:296
          throw err;
          ^

Error: template not found: template.html

如何在index.js中引用打包的模板文件,因此它使用 package 中的模板( /usr/local/lib/node_modules/node-nunjucks/template.html中的模板)而不是在我的工作目錄?

配置調用是您要調整的調用。 它告訴 getTemplate 在哪里尋找模板。 它可以采用一組值,這些值引用了可以找到模板的多個目錄。

例子:

#!/usr/bin/env node
var nunjucks = require('nunjucks');

var env = nunjucks.configure(['./', './node_modules/node_nunjucks/']);
var template = env.getTemplate('inner.html');
var output = template.render({
  h1_copy: "Foo and Bar"
});
var template2 = env.getTemplate('outer.html');
var output2 = template2.render({
  h1_copy: "Foo2 and Bar2"
});


console.log(output);
console.log(output2);

在此示例中,inner.html 位於 index.js 旁邊的根目錄中,outer.html 位於 node_modules/node_nunjucks 中。 它只是 node_modules 文件夾的相對路徑,但是您可以使用別名和諸如此類的東西變得更聰明,具體取決於您使用什么工具來構建。

希望有幫助。

暫無
暫無

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

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