繁体   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