X

Jade Node.js Template Engine DataBinding Part 3

Jade

In my previous post I showed the basic syntax of jade when using express application in node.js, in this post I will go over the DataBinding aspects of jade template engine.

Jade Node.js Template Engine DataBinding through Interpolation

Jade provides interpolation of variables using the #{} syntax, Hash, Curly Brackets.
For example if we have a variable called name with a value of John, to display from our controller in Express Web Application in Node through jade, we will code it like

p Hello my name is #{name}

//output

Hello my name is John

We can also declare a variable inside the jade file, using the dash and var (although the var is optional), as the example shows below one can also access an array or hashtable like syntax.

- var name = "john"
p Hello my name is #{name}

- list = ['a', 'b', 'c']
p Lets learn the #{list[0]}, #{list[1]}, #{list[2]}

- items = {"name": "john", "age": "5" }
p #{items.name} is #{items.age} years old.

//output

Hello my name is john

Lets learn the a, b, c

John is 5 years old.

Shortcuts

jade also provides a shortcut rather than using the interpolation syntax, by using just the “=” sign or by directly accessing the declared variables.

- lorem = "This is a sample lorem ipsum text, that isnt quite lorem ipsum"

p= lorem

- x = {"name": "john", "age": "5" }

input(type="text", name=x.name, value=x.age)
//output

This is a sample lorem ipsum text, that isnt quite lorem ipsum

How to escape HTML

Sometimes we have to escape html in a string, even though jade prevents us from XSS, we may come across a situation we a using a wysiwyg editor, that requires non encoded text.
Jade allows us to escape html by using the “!” syntax, for both shortcut and non shortcut curly brackets syntax.

- name = "Hello John"
p!= name

- test = "test abc"
p !{test}
//output 

Hello John

test abc

Hope you enjoy the series I will continue with our next blog with how to use filters and logic in Jade.

Taswar Bhatti:

View Comments (1)

Related Post