Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 533
Kiran Avatar asked Jan 06 '14 00:01

Kiran


3 Answers

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

like image 130
Andrey Sidorov Avatar answered Oct 27 '22 22:10

Andrey Sidorov


I realize this is really old, but when you declare a function in jade, you need to do

script.

not

script

the period makes the difference and will allow jade to pick up that it's in fact a piece of code, rather than HTML.

like image 28
user1241388 Avatar answered Oct 27 '22 21:10

user1241388


By this #{capitalize(itemName)} you are trying to call function that is passed to the template from the controller (back-end).

For instance (/routes/index.js):

res.render('index', { title: 'Express test', fs : { echo : lang} });

While in index.jade

 a(href='/register') #{fs.echo('xxx')}

where

lang

is a function defined earlier that takes some parameter.

like image 35
gregiolo Avatar answered Oct 27 '22 23:10

gregiolo