In this blog post we will see more advanced usage of handlebar template engine with express
In our previous tutorial we saw how to create a helloworld application using handlebar with express, here we will see more advanced usage of handlebar.
Variables
We have seen already how to pass variables in our route files, now to access those variables in our view files is easy
[code]
{{variable_name}}
[/code]
If Condition/Each Loop with Handlebar
If conditions and for loops are quite easy
[code]
{{#if variable}}
//if true
{{else}}
//if flase
{{/if}}
{{#each array_variable}}
//loop
{{else}}
//if array empty
{{/each}}
[/code]
Handlebar Helpers
Most of the time we require advance logic in our templates, not just simple if and for loops. For those instances we use helpers. Through helpers we can write javascript functions and call them inside templates.
Below we have created an helper function called “canDisplayDeal”. The function is defined in index.js routes file and is called in the handlebar template.
More details about helpers http://handlebarsjs.com/block_helpers.html
The entire code base for this is available here
https://github.com/manishiitg/excellence_magento_blog/tree/master/nodejs/express/tutorial4
Experiments
1. Implement the bootstrap starter template using handlebars (http://getbootstrap.com/examples/starter-template/)
2. Create an helper function using the above “deals” json object. If the string length “name” in deals is greater than 10, add … and truncate the name else output it as it is.