Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
436 views
in Technique[技术] by (71.8m points)

node.js - javascript function execution inside jade template

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

unexpected text ;

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...