要在 pug 模板中生成随机字符串,我想使用 random-string javascript 模块。
首先我像这样通过 npm 安装它:
npm install random-string
然后在 pug 模板中我使用了这个:
.site
.title
- var string = randomString({length: 20});
| #{string}
但是在编译文件时我得到了这个错误:
randomString is not a function
如何在 pug js temaplte 中使用第三方 javascript 函数?
最佳答案
除非在调用它的文件(例如 Controller )中调用 render()
时传入,否则您的 pug 文件不会有 randomString 范围。
例如
this.render("[pugFilename]", {
randomString = require("randomstring") // whatever package name you're using
}
就我个人而言,我更喜欢在 View 之外以及在请求渲染 View 的脚本中尽可能地做任何非 View 的事情。
否则,Pug 中的语法会开始看起来非常困惑,并且变得难以理解。
您可以用问题中的代码切换上面的代码,它应该可以正常工作,但我建议您将变量名称(或键)更改为更有意义的名称。
例如
this.render("[pugFilename]", {
randomStr: randomString({ length: 20 })
});
关于javascript - 如何在 pug js 模板中使用 javascript 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45158001/