handlebars

Handlebars – A More Dynamic Way

Dagin Fullmer JavaScript, Single-Page Application, Technology Snapshot, Tutorial Leave a Comment

Introduction

Handlebars.js is a popular templating engine extension to the Mustache template language. While this post is not intended as an introduction to Handlebars, make sure to visit the Handlebars’ website here for that introduction.

In this post, we’ll take a more philosophical role. We will explore how Handlebars is a dynamic template creation tool and what benefits logic-less templates afford us. During our discussion we will cover Handlebars’ precompiling, partials, and helpers, and how each supports or contradicts dynamic and logic-less templates.

Static and Dynamic

When it comes to developing html structure, there are two main avenues of thought: static and dynamic.
Static html construction is a one-to-one relationship of page-to-purpose. A single html document would display one, and only one, specific web page as part of a multi-page website.

Dynamic html construction is the culmination of a multipurpose page, capable of modifying its content to suit different uses. This often lends itself to single-page web applications.

The issue with static pages is that they can only be used once for its intended purpose. There exist many ideas of how best to implement a dynamic web-based solution. I have found that Handlebars does a good job in simplifying dynamic html construction.

handlebars1
versus

handlebars2

Given the above examples, we see that while Handlebars is programmatically equivalent to the code-based implementation. It also provides readability and maintainability. A static page must rely heavily upon DOM (Document Object Model) insertions to display similarly to those dynamically built.

Also, while the code-based implementation could provide a faster process time (marginally), the readability is lessened. As structure and code is closely coupled the scalability is decreased. Handlebars’ emphasis on separation of concerns allows template enhancements or defects to be resolved quickly and effectively.

To Pre-Compile or Not to Pre-Compile

One of the main questions that should be considered when building Handlebars templates is whether we should compile or pre-compile our templates. Standard Handlebars compilation occurs during runtime while pre-compilation occurs during the build process, before deployment.

It is my opinion that there isn’t much excuse not to pre-compile Handlebar templates. Pre-compiled templates continue to offer dynamic solutions while both utilizing the smaller Handlebars runtime library and reducing browser computation time. This leads to faster page loads and a smoother user experience, especially as the application grows.

handlebars3

*Templates were processed 1000 times each. The last number indicates the number of milliseconds required to process each template.

The world of NodeJS, and consequently NPM, is vast, intimidating, and outside the scope of this discussion. It is an excellent tool which greatly simplifies and enables front end development. I mention it solely to introduce the grunt-contrib-handlebars package. Installation and setup can be found here.

Through use of the grunt-contrib-handlebars, we can automate (to an extent) the pre-compilation process for all our Handlebars templates.

handlebars4

*With the given configuration templates can be called with: Templates.<filename>(<context>).

By this point, the process of building our Handlebars templates has been greatly simplified.

handlebars5

Partials

One cool feature of Handlebars is the ability to call a template from within another template. Template inception? Templateception? Lame? You decide. These templates are referred to as “partials.” Partials can be utilized within other templates or act as standalone templates themselves.

If a template is intended as a partial, it must be registered as such. To register a template as a partial we’ll need to modify our Handlebars file accordingly. All that is required is to put an underscore ‘_’ prepended to the file name.

I prefer to register all templates as partials, thus ensuring the option exists to choose between partials or standalone templates.

Partials are of vital importance as it simplifies and streamlines the html build process. There are multiple coding techniques that can replicate the same end result, albeit, in a more convoluted orchestration.

handlebars6

Other benefits include the ability to use preconfigured templates to quickly insert items into a list. Also, to enable quick sorting and rendering of one list while not affecting other elements on a page. This modularity of template creation lends itself well to the development process.

In code development, redundant functionality and/or large segments should be broken up into smaller, more maintainable sections. This same philosophy can be mirrored within template creation.

Logic-Less Versus Logic-Full

The debate between logic-less and logic-full template structure is a long one. Both sides of the debate hold strong opinions about why their process is superior.

Logic-less is the idea that html templates shouldn’t incorporate logic statements of any kind, and that the work of building dynamically should be handled separately within a different, yet associated, file.

Logic-full plays opposite to logic-less by suggesting that both template and business logic should be tightly coupled, oftentimes within the same file.

While logic-less is almost completely unattainable without going to great lengths to separate concerns, code, and everything else, the concept should be more appropriately named less-logic. Ideally, a less-logical approach would encourage readability and maintainability while sacrificing the full power of whichever programming language is being utilized. Handlebars, while traveling down the logic-less road, is designed to give templates the option of being as logic-light or logic-heavy as desired.

Regardless of which philosophy you subscribe, Handlebars is a lightweight tool that can accommodate both. As with all tooling there are caveats and possibly some items which you may entirely disagree. That being said below is some of the more intermediate to advanced concepts that Handlebars addresses.

Registered Helpers

Another feature of Handlebars is the idea of registered helpers. These helpers are additional functionality, logic, which can be customized and inserted into a template. Some of these helpers already exist as if statements and iterators.

Handlebars, in keeping with logic-less methodologies, provided a bare minimum of such functionality. However, Handlebars doesn’t limit the addition of more logic if the development team decides to take a more logic-full route.

For logic-less route we may want to provide a JSON translator to sanitize the template context. This would eliminate the need of multiple registered helpers. In contrast, a logic-full route would convert and sanitize the data during template construction.

Conclusion

As I begin a web application, my first thought usually goes to the structure. The html structure helps me visualize and identify the overall feel of the application. The nice thing about Handlebars is that it visually represents the DOM while allowing a dynamic element as things change.

Is Handlebars the only solution that offers this? No. However, in my experience its capabilities make it a very appealing library for front end development.


About the Author
Dagin Fullmer

Dagin Fullmer

Twitter

Dagin Fullmer is a Keyhole Software Consultant specializing in single-page web applications and full-stack development. Outside of development, Dagin spends his time as a father, husband, board game enthusiast, and bookworm. His favorite quote is “Being vague is almost as fun as that other thing.”


Share this Post

Leave a Reply