在Pug模板中添加JavaScipt有很多问题,包括:
- PugJS对许多完全有效的JavaScript函数抛出异常
- 当您的JavaScript函数出现语法错误时,不会为您识别它们
- 不能在Pug模板中的JavaScript函数中设置断点
- 您不能使用Typescript来帮助提高健壮性
在Pug中使用JavaSript函数的首选/推荐方式是什么?
在意识到有更好的选择之前,我与这些问题斗争了一段时间。我建议将JavaScript函数传递给Pug渲染函数,而不是将它们构建到模板中。
我之前做的是这个JavaScript
const render = pug.compileFile(path.join(__dirname, '../templates/sandbox.pug'));
const html = render({});
和这个Pug模板
- var testFunc = function(){
- return "Test func";
- }
div #{testFunc()} worked!
实现同样效果的更好方法是使用这个JavaScript
const render = pug.compileFile(path.join(__dirname, '../templates/sandbox.pug'));
const html = render({
testFunc: function(){
return "Test func";
}
});
和这个Pug模板
div #{testFunc()} worked!
这允许您设置断点,使用Typescript和所有其他很酷的东西,并避免了与解析JavaScript不太好相关的所有Pug错误。