Pug call js function from another file inside template
Asked Answered
C

5

13

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?

Capet answered 8/5, 2017 at 1:35 Comment(0)
P
11

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.

Prokopyevsk answered 8/5, 2017 at 5:41 Comment(0)
E
4

In PUG options use locals property to import functions you want to use inside your templates.

const calculateAge = require('./calculate-age');

const config = {
  pug: {
    locals: {
      calculateAge,
    },
  },
};

Then you can use it in all your templates like this (please note the extra unescaping tag !{}):

p Age: !{calculateAge(pet.birthYear)}
Explorer answered 22/3, 2019 at 14:46 Comment(6)
I use Expressjs. Where exactly should I put the configuration code?Unpractical
@Unpractical Does this help you? app.locals.foo = 'foo'; pugjs.org/api/express.htmlExplorer
Where do you put the configuration code?Joletta
Downvoting as this doesn't explain where to pass the config objectBlowout
What the heck is "PUG options" ?Mesdames
It depends how you use PUG. In my case, I used PUG via Gulp. If you use Express then locals does not refer to PUG options but Express options. See expressjs.com/en/4x/api.html#app.locals However, the PUG itself have options as well pugjs.org/api/reference.html#options It really depends in what stack you use it.Explorer
R
2

Make your function available in pug like this:

//assuming you're using express
app.set('view engine', 'pug');
app.locals.someFunction = input => input * 5;
// or
import {someOtherFunction} from "packageOrFile";
app.locals.someOtherFunction = someOtherFunction;

In your pug you then can do

span= someFunction(10)
span= someOtherFunction(123)

This is basically what mahish wrote in his comment, but it actually answers the question satisfactory and here's the documentation.

Remind answered 10/1, 2023 at 19:17 Comment(0)
M
0

Like in raw HTML if you want JS to execute in a sepcific part you need a script tag to enclose the js you want to use.

 span.species= (pet.species)
 p Age:
     .script 
         calculateAge(pet.birthYear) 
 if pet.favFoods
Mig answered 8/5, 2017 at 1:39 Comment(0)
S
-2

You can write javascript with .script tag

 script.
   $( document ).ready(function() {
   calculateAge(params)
 })
Scorpaenoid answered 19/5, 2017 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.