且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Pug 从模板内的另一个文件调用 js 函数

更新时间:2023-02-11 19:07:27

可能有更好的方法来处理这个问题,但我通常通过导入外部模块然后将其作为模板上下文对象的一部分传递来实现.这意味着呈现模板的代码应该类似于:

There may be better way to handle this, but I usually do it by importing the external module and then passing it as part of template context object. That means the code that renders the template should be something like:

const calculateAge = require("calculateAge"); // change path accordingly

router.get("/main", function(){
  let pageInfo = {};
  pageInfo.title = "Demo";
  pageInfo.calculateAge = calculateAge;
  res.render("main", pageInfo);
});

现在,您可以在模板中访问 calculateAge.如果这个模块在大多数模板中被大量使用,那么你应该将它作为 res.localsapp.locals 的一部分传递,以便它可用于所有模板无需为每个路径请求附加它.

Now, you can access calculateAge in your template. If this module is used a lot in most of the templates, then you should pass it as part of res.locals or app.locals so that it is available for all templates without the need to append it for every path request.