Chapter 5. Dynamic HTML with Handlebars

One of the most important features when creating a website is the ability to display dynamic content on an HTML page. The difference between dynamic content and static content is that dynamic content is typically generated via conditional statements and/or varying data (usually retrieved from a database). In order to generate parts of an HTML page during runtime, you will need some sort of rendering engine. There are many different rendering engines available that can be used with Node and Express. The particular engine we chose for this book is Handlebars.js—named for the syntax use of {{ and }} that resembles a handlebar mustache!

Basic syntax for Handlebars

The basic syntax for Handlebars is really quite simple. Let's assume the following JavaScript object is passed to a Handlebars template:

var model = {
  name: 'World'
};

The template file itself will contain the following markup:

<div>
  Hello {{ name }}!
</div>

This file would render to a browser in the following way:

Hello World!

Of course, there's a lot more that you can do than just this! Handlebars also supports conditional statements:

var model = {
  name: 'World',
  description: 'This will only appear because its set.'
};

<div>
   Hello {{ name }}!<br/><br/>
  {{#if description}}
     <p>{{description}}</p>
  {{/if}}
</div>

Using an if block helper as shown in the preceding code, you can check for truthy conditionals and only display HTML and/or data if the condition is true. Alternatively, you can use the unless helper to do the opposite, and display HTML only if a condition is falsey:

var model = {
  name: 'World'
};

<div>
   Hello {{ name }}!<br/><br/>
  {{#unless description}}
     <p>NOTE: no description found.</p>
  {{/if}}
</div>

You can use both if and else as well as unless the same way you would use conditional if/else in other programming languages.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.217.55