简体   繁体   English

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

[英]Pug call js function from another file inside template

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:这就是问题所在,我正在使用 pug/jade 模板,我想在 pug 模板中调用 function 来转换一些数据这是主模板:

 /** 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:这是外部 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? shell 我该怎么做才能做到这一点?

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. 现在,您可以访问模板中的calculateAge 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. 如果此模块在大多数模板中使用较多,则应将其作为res.localsapp.locals一部分传递,以便它可用于所有模板,而无需将其附加到每个路径请求中。

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. 就像在原始HTML中一样,如果您希望JS在一个单独的部分中执行,则需要一个脚本标签来封装要使用的js。

 span.species= (pet.species)
 p Age:
     .script 
         calculateAge(pet.birthYear) 
 if pet.favFoods

In PUG options use locals property to import functions you want to use inside your templates. 在PUG选项中,使用locals属性导入要在模板中使用的功能。

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)}

Make your function available in pug like this:让你的 function 在 pug 中可用,如下所示:

//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 .这基本上是 mahish 在他的评论中写的,但它实际上回答了令人满意的问题, 这是文档

You can write javascript with .script tag 您可以使用.script标签编写javascript

 script.
   $( document ).ready(function() {
   calculateAge(params)
 })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM