Building Blocks of Handlebars

ryan-lewis-v4

Welcome to Part 2 of this review of the Pluralsight course JavaScript Templating with Handlebars by Ryan Lewis.

Ryan is a Software Engineer who specializing in ambitious single page web applications. He works on a platform providing customer support sites to over 100 separate brands. Ryan teaches Java and JavaScript to aspiring web developers and technology professionals at the University of Washington and Seattle Central College.

Also see Part 1: JavaScript Templating with Handlebars

Building Blocks of Handlebars

Demo Application Walkthrough

Ryan shows us the internationally popular game/dating app “Dog or Not?”

This includes the ability to switch to from English to Dog language and back.

You can find the code for this project at https://github.com/ryanmurakami/pluralsight-handlebars-starter-code

Handlebars, jQuery, MDL

Again we’re using Bower to help manage our dependencies. We need three dependencies Handlebars, jQuery, Material Design Lite.

This course uses Handlebars v3.0.3. The latest version at the time of writing is v4.0.5 which is 159,586 bytes uncompressed and unminified.

$ bower install --save jquery handlebars#v3.0.3 material-design-lite

Handlebars Expressions

All handlebars expressions are wrapped in the {{handlebars}} and the handlebars engine only sees the handlebars expressions in the HTML.

Ryan explains how to render a template with the compile method. Here’s his example:

var template = 'My name is {{name}}.';
var compiled = Handlebars.compile(template);
var rendered = compiled({ name: 'Ryan' });

Ryan calls this the “handlebars dance”

– Get Template
– Compile Template
– Render with Data
– Insert Rendered HTML

Ryan also talks about Nested Paths in Mustache.
If a property is an object with it’s own properties, according to the Mustache specification we should add expressions inside expressions.
If we need multiple levels of this, you can imagine how complex this would get.

A much better solution is Handlebars dot and bracket notation:

Name: {{myObj.name}}
Age: {{myObj.age}}
Address: {{myObj.address.street}}
{{myObj.address.city}}, {{myObj.address.state}}
{{myObj.address.zipcode}}

See http://handlebarsjs.com/expressions.html

Localization with Handlebars

Again, you can download the code from https://github.com/ryanmurakami/pluralsight-handlebars-starter-code

In this demo, a big block of HTML is moved into a script tag with the type “text/x-handlebars-template” and id “index-template”.
Ryan says the type is not very important but gives you syntax highlighting inside Atom.

He writes app.js with a renderPage() function. This function does the handlebars dance

var template = $('#index-template').html(),
compiled = Handlebars.compile(template),
rendered = compiled(window.language);
$('#main').html(rendered);

Ryan also shows how to implement the language switch feature.

In index.html he replaces the hardcoded html strings with handlebars expressions.

One of the advantages of templating is we can reuse the same handlebars expression in multiple parts in our site and only need to set the value once.
Say we had three different elements all holding the same string value. With jQuery alone we might do something like this:

$('#element1').text(siteTitle);
$('#element2').text(siteTitle);
$('#element3').text(siteTitle);

Or if we were a little smarter we might make each element a member of the same CSS class and do:

$('.siteTitleElement').text(siteTitle);

With handlebars we don’t need to create a new CSS class.

Ryan shows us that the “Dogs or not?” app works as it did before.

Iterating Through Arrays

Handlebars has the concept of Blocks. Each block has at least two expressions.

The opening expression begins with the # symbol.
The closing expression begins with the / symbol.

Both the opening and closing expression has the same property.

Ryan shows a simple example of a handlebars block:

{{#dog}}
{{name}}
{{breed}}
{{/dog}}

There is a built in each helper that we can use with our block:

{{#each dogs}}
{{this}}
{{/each}}

Ryan explains that unlike standard handlebars expressions, helpers take additional arguments.

We see another example that outputs user names and images.
Each user is an object inside an array of users, and the template data defines the values for our users.

Ryan shows how to put all of this data into the application, refactoring our code to take advantage of the handlebars each helper

Next, he introduces us to @data variables. These are special properties in Handlebars for use in helpers.

An example of this is @root, which gets the root context of the template.

Ryan also writes a renderDogs function in app.js

See http://handlebarsjs.com/block_helpers.html

For more on the if, unless, See http://handlebarsjs.com/builtin_helpers.html

Logic for your Logic-less Templates

Mustache’s slogan is “Logic-less templates” but Handlebars contains some logic. It comes with if/else helpers.

Ryan explains that this isn’t heresy.
He says Mustache also contains a little logic, with Mustache blocks that only execute if the property exists.
Mustache also has and inverted version of this, effectively an else block!

I find handlebars if / else blocks to be more familiar and readable than the original Mustache technique. There is also an unless helper which does the same thing as the inverted (falsy) Mustache expression.

{{#if truthyOrFalsy}}
truthy
{{else}}
falsy
{{/if}}

Ryan shows us that we can use this with the each helper:

{{#each dogs}}
{{dog_stuff}}
{{else}}
No dogs!
{{/each}}

Ryan writes an attachDogButtons function which handles the “dog-button” and “not-dog-button” click events.

And again the dog or not? application continues to work great.

Modularization with Partials

Ryan describes partials as “basically mini-templates”.

We can use them for modularizing templates, either for sanity, or to remove redundancy.

Templates can get long a complicated. Ryan gives the example of breaking out a long form into:

– Header partial
– Article partial
– Comments partial
– Footer partial

Ryan describes how to register a partial. It’s easy, we just use the registerPartial function.

See http://handlebarsjs.com/partials.html

Escaping HTML and Removing Whitespace

By default, Handlebars escapes HTML text when rendering it through expressions.

If you want to display the raw HTML instead, you can use three handlebars on either side {{{like-this}}}

Ryan also shows how to remove Whitespace within your expression. We use the ~ character on either or both sides to the expression:

{{~prop1~}}

Ryan says this is only for our benefit as it only changes the HTML view, not the look of the output rendered in the browser.

That’s it for this review. The full course also contains modules on Harnessing the Poer of Helpers, and moving Beyond the Basics. Check it out here.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s