Instant Handlebars.js
上QQ阅读APP看书,第一时间看更新

So, what is Handlebars?

To answer this properly, we need to first understand what a templating engine is, or better, what it comes to accomplish. Any dynamic site (blog, store, and so on) has parts which remain static, and at least rules on how the dynamic data should be inserted. A templating engine can and should be thought of as a new language in its own right and has a specialized syntax made specifically for rendering views.

Before templating engines you would have some kind of code in your actual DOM pages, through which you would insert the dynamic pieces of data at specific points. This is not great code separation, and it's definitely not a very clean option. A templating engine is meant to augment this step with its specialized syntax made specifically for this purpose; if done right, you should end up with clean and reusable templates, and leave your app clear of any bodge code.

Mustache was a pretty popular templating library for years and has basically been ported to nearly every programming language available. The problem with Mustache is that it is fairly opinionated on how you should write your templates; it follows a strict "View-Controller" separation and is a purely logic-less engine made specifically for replacing expressions with pre-computed data. Handlebars is a superset of the Mustache library, that adds a lot of logic and extensibility, making it a more flexible solution, while still retaining full backward compatibility, so that any Mustache templates can work out of the box. Following are the features of Handlebars:

  • It has a very simple and easy to write syntax
  • It allows you to add some logic using helpers but still separates it from the actual template's code to keep them easy to manage
  • It's very fast and allows you to pre-compile your templates in JavaScript

Because of this, Handlebars has become the premier choice when it comes to frontend templates and is currently being used in many of the popular frameworks such as Meteor and Ember.js.

Not to mention the fact that it was built by the legendary Yehuda Katz, who is a core member on projects such as, jQuery, Ruby on Rails, and the Ember.js framework.