我将近四个小时都无法解决这个问题,而且我找不到任何对此类问题有帮助的文档。这就是问题所在,我正在使用 pug/jade 模板,我想在 pug 模板中调用函数来转换一些数据 这是主模板:
/** 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 **/
我要做什么 shell 才能做到这一点?
最佳答案
可能有更好的方法来处理这个问题,但我通常通过导入外部模块然后将其作为模板上下文对象的一部分传递来实现。这意味着呈现模板的代码应该类似于:
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
的一部分传递,以便它可用于所有模板无需为每个路径请求附加它。
关于javascript - Pug 从模板中的另一个文件调用 js 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43838511/