Pug call js function from another file inside template
javascript, pug, templates
Solution
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);
});
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.
Problem
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 **/ ``` This is the external function: ``` /** 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?