Pug 从模板内的另一个文件调用 js 函数 [英] Pug call js function from another file inside template
问题描述
我将近四个小时都无法解决这个问题,而且我找不到任何有关此类问题的有用文档.这就是问题所在,我正在使用 pug/jade 模板,我想在 pug 模板中调用函数来转换一些数据这是主模板:
I can't solve this for almost four hours, and i can't find any helpful documentation for this kind of problems. This is the issue, I'm using pug/jade templates and i want to call function inside pug template to transform some data This is the main template:
/** main template */
section
each pet in pets
.pet
.photo-column
img(src= pet.photo)
.info-column
h2= pet.name
span.species= (pet.species)
p Age: #{calculateAge(pet.birthYear)} //here I need to call calculateAge function
if pet.favFoods
h4.headline-bar Favorite Foods
ul.favorite-foods
each favFood in pet.favFoods
li!= favFood
/** end main template **/
这是外部函数:
/** calculateAge.js **/
module.exports = function(birthYear) {
var age = new Date().getFullYear() - birthYear;
if (age > 0) {
return age + " years old";
} else {
return "Less than a year old";
}
};
/** end calculateAge.js **/
我做了什么外壳来实现这一点?
What shell I do to make this happen?
推荐答案
可能有更好的方法来处理这个问题,但我通常通过导入外部模块然后将其作为模板上下文对象的一部分传递来实现.这意味着呈现模板的代码应该类似于:
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.locals
或 app.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.
这篇关于Pug 从模板内的另一个文件调用 js 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!