如何在pugjs模板中使用javascript模块

如何在pugjs模板中使用javascript模块,javascript,node.js,pug,Javascript,Node.js,Pug,为了在pug模板中生成随机字符串,我想使用javascript模块 首先,我通过npm安装它,如下所示: npm install random-string 然后在pug模板中,我使用了以下内容: .site .title - var string = randomString({length: 20}); | #{string} 但在编译文件时,我遇到了以下错误: randomString is not a function 如何在pug js Tema

为了在pug模板中生成随机字符串,我想使用javascript模块

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

npm install random-string
然后在pug模板中,我使用了以下内容:

.site
   .title
       - var string = randomString({length: 20});
       | #{string}
但在编译文件时,我遇到了以下错误:

randomString is not a function
如何在pug js Temapte中使用第三方javascript函数

phpStorm文件监视程序的更新 首先,在本地安装pug cli和随机字符串

npm install pug-cli random-string --save
然后安装文件监视程序

原始答案 设置并要求随机字符串作为局部变量,然后可以在模板中访问它。比如说,

哈巴狗

.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>

除非在调用它的文件(例如控制器)中调用
render()
时传入,否则您的pug文件将不具有randomString的作用域

e、 g

就我个人而言,我更喜欢在视图之外和请求渲染视图的脚本中(如果可以的话)执行任何非视图内容

帕格中的语法可能开始看起来非常混乱,否则就很难理解

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

e、 g


可以,但需要将其作为
pug
渲染参数传递,因为在
pug
中不能
require
。只需在外部上下文中
require
并传递它。我正在使用phpStorm watcher编译整个项目中的所有.pug文件。我在哪里可以配置您的指令?@A.B.Developer您是否在使用pug cli和phpStorm file watcher?您可以将
-O'{randomString:require(“randomString”)}'传递给watcher设置中的参数。我将
-O'{randomString:require(“randomString”)}'添加到参数中,但现在我在编译时遇到了以下错误:
未定义:1({randomString:)^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pug -O "{randomString: require('random-string')}" template.pug
this.render("[pugFilename]", {
    randomString = require("randomstring") // whatever package name you're using
}
this.render("[pugFilename]", {
    randomStr: randomString({ length: 20 })
});