在jade模板中执行javascript功能 [英] javascript function execution inside jade template

查看:106
本文介绍了在jade模板中执行javascript功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是nodejs的新手,并尝试为html内容创建一个玉石文件 myfile.jade
这里是文件的内容: p>

I am new to nodejs and trying to create a jade file for the html content myfile.jade: Here are the contents of the file:

extends layout
block content
   script
     function capitalize(s) { 
       console.log("Testing js exec");
       return s.charAt(0).toUpperCase() + s.slice(1); 
     };
  table
    - each item in list
      tr
        td
          a(href="/collection/#{item.name}") #{capitalize(itemName)}

但是,运行时会抛出以下错误:

However, when running it throws the following error:

Error: mweb/views/collections.jade:8
    6|   script
    7|     function capitalize(s) { 
  > 8|       console.log("Testing js exec");
    9|       return s.charAt(0).toUpperCase() + s.slice(1); 
    10|     };

意外文字;

如果我删除console.log,它会引发错误:

If I remove console.log, it throws the error saying:

TypeError: mweb/views/collections.jade:18
  > 18|             a(href="/collection/#{item.name}") #{capitalize(itemName)}

据我所知,在玉编辑期间,大写被调用,并且该函数不可用,因为脚本标签也被编译到html中。在
a)服务器端或
b)客户端,我有什么最好的方法?

As far as I realized, capitalize is being called during the jade compilation and the function is not available as the script tag is also compiled into the html. What is the best way for me to have this call evaluated on a) server side or b) client side?

Thx

推荐答案

您需要在jade范围内定义函数,而不是在JS中生成:

You need to define function in the scope of jade, not in JS you generate:

block content
   -  function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); };
  table
    - var list = ['one', 'two']
    - var itemName = 'test test'
    - each item in list
      tr
        td
          a(href="/collection") #{capitalize(itemName)}

但是最好将它放在模板之外,并将引用传递给帮助对象

but it's probably better to have it outside of template and pass reference to helpers object

这篇关于在jade模板中执行javascript功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆