如何在pug js模板中使用javascript模块

时间:2017-07-18 05:11:23

标签: javascript node.js pug

要在pug模板中创建随机字符串,我想使用random-string javascript模块。

首先我通过npm安装它,如下所示:

npm install random-string

然后在帕格模板中我使用了这个:

.site
   .title
       - var string = randomString({length: 20});
       | #{string}

但是在编译文件时我遇到了这个错误:

randomString is not a function

如何在pug js temaplte中使用第三方javascript函数?

2 个答案:

答案 0 :(得分:1)

你的pug文件不具有randomString的范围,除非你在调用它的文件中调用render()时传入它(例如你的控制器)。

e.g。

this.render("[pugFilename]", {
    randomString = require("randomstring") // whatever package name you're using
}

就个人而言,我更喜欢在视图之外以及请求渲染视图的脚本中执行任何非视图内容,我可以在哪里。

Pug中的语法可能会开始变得非常混乱,否则很难理解。

您可以使用问题中的代码切换上面的代码,它应该可以正常工作,但我建议您将变量名称(或键)更改为更有意义的内容。

e.g

this.render("[pugFilename]", {
    randomStr: randomString({ length: 20 })
});

答案 1 :(得分:0)

phpStorm文件观察器的更新

首先,在本地安装pug-cli和random-string,

npm install pug-cli random-string --save

然后设置文件观察器,

enter image description here

原始答案

设置并要求random-string作为局部变量,然后您可以在模板中访问它。例如,

template.pug

.site
   .title
       - var string = randomString({length: 20});
       | #{string}

使用pug编译它

const pug = require('pug');

// Compile template.pug, and render a set of data
console.log(pug.renderFile('template.pug', {
  randomString: require('random-string')
}));
//-> <div class="site"><div class="title">o0rGsvgEEOHrxj7niivt</div></div>

如果您使用的是pug-cli,请在pug-cli的相同范围内安装random-string,并通过字符串或文件指定选项。

pug -O "{randomString: require('random-string')}" template.pug