在Pug模板中添加JavaScript会遇到许多问题,包括:
- PugJS对许多JavaScript函数抛出异常,而这些函数实际上是完全有效的。
- 当你的JavaScript函数存在语法错误时,Pug不会为你识别出来。
- 你不能在Pug模板中的JavaScript函数中设置断点。
- 你不能使用TypeScript来提高鲁棒性。
那么,在Pug中使用JavaScript函数的首选/推荐方式是什么?
在Pug模板中添加JavaScript会遇到许多问题,包括:
那么,在Pug中使用JavaScript函数的首选/推荐方式是什么?
在意识到更好的解决方案之前,我曾经为这些问题苦苦挣扎。我建议将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!
const render = pug.compileFile(path.join(__dirname, '../templates/sandbox.pug'));
const html = render({
testFunc: function(){
return "Test func";
}
});
还有这个 Pug 模板
div #{testFunc()} worked!