【问题标题】:Pug call js function from another file inside templatePug 从模板内的另一个文件调用 js 函数
【发布时间】:2017-05-08 01:35:18
【问题描述】:

我花了将近四个小时都无法解决这个问题,而且我找不到任何有用的文档来解决这类问题。这就是问题所在,我正在使用 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 **/

我做了什么外壳来实现这一点?

【问题讨论】:

    标签: javascript templates pug


    【解决方案1】:

    可能有更好的方法来处理这个问题,但我通常通过导入外部模块然后将其作为模板上下文对象的一部分传递来做到这一点。这意味着呈现模板的代码应该是这样的:

    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.localsapp.locals 的一部分传递,以便它可用于所有模板,而无需为每个路径请求附加它。

    【讨论】:

      【解决方案2】:

      在 PUG 选项中,使用 locals 属性导入要在模板中使用的函数。

      const calculateAge = require('./calculate-age');
      
      const config = {
        pug: {
          locals: {
            calculateAge,
          },
        },
      };
      

      然后你可以像这样在所有模板中使用它(请注意额外的非转义标签!{}):

      p Age: !{calculateAge(pet.birthYear)}
      

      【讨论】:

      • 我使用 Expressjs。我应该把配置代码放在哪里?
      • @user8555937 这对您有帮助吗? app.locals.foo = 'foo';pugjs.org/api/express.html
      • 配置代码放在哪里?
      【解决方案3】:

      就像在原始 HTML 中一样,如果您希望 JS 在特定部分中执行,您需要一个脚本标签来包含您要使用的 js。

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

      【讨论】:

        【解决方案4】:

        你可以用.script标签写javascript

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

        【讨论】:

          猜你喜欢
          • 2018-03-20
          • 1970-01-01
          • 2017-11-28
          • 1970-01-01
          • 2023-02-01
          • 2022-01-06
          • 1970-01-01
          • 1970-01-01
          • 2022-06-10
          相关资源
          最近更新 更多