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
1 2 3 4 |
p Hello my name is #{name} //output <p>Hello my name is John</p> |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
- 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 <p>Hello my name is john</p> <p>Lets learn the a, b, c</p> <p>John is 5 years old.</p> |
Shortcuts
jade also provides a shortcut rather than using the interpolation syntax, by using just the “=” sign or by directly accessing the declared variables.
1 2 3 4 5 6 7 8 9 10 |
- 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 <p>This is a sample lorem ipsum text, that isnt quite lorem ipsum</p> <input type="text" name="john" value="5" /> |
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.
1 2 3 4 5 6 7 8 |
- name = "Hello <b>John</b>" p!= name - test = "test <i>abc</i>" p !{test} //output <p>Hello <b>John</b></p> <p>test <i>abc</i></p> |
Hope you enjoy the series I will continue with our next blog with how to use filters and logic in Jade.
Excellent post on data binding. Helped me with a lot of my syntax issues with Jade. Thank you!