• Home
  • blog
  • Using Inline Partials and Decorators with Handlebars 4.0

Using Inline Partials and Decorators with Handlebars 4.0

Handlebars is one of the most widely used JavaScript templating libraries for both client-side and server-side rendering. It implements the mustache specification but adds some extra sauce to make working with templates easier. If you’re new to Handlebars and want to know more, I suggest you to check out my Pluralsight course on JavaScript Templating with Handlebars to learn how to get started.

Handlebars version 4.0 landed in September 2015 and brought two major new features with it: Inline Partials and Decorators. In this article, we’re going to take a look at both features, explain their syntax and when you should use them. By its end, you should feel comfortable using both features to take your templating game to the next level!

Inline Partials

Partials are a common templating concept not unique to Handlebars. The idea behind it is to create templates that are likely to be re-used, separate them into their own file (a Partial), and then use them in different templates. You may think at Partials as a simple a tool to modularize your templates.

In Handlebars, Partials might not be the most convenient structure to work with. First of all, all partials are global. That means this tool may work for your application, but having little control over it could become a problem in large applications. Secondly, partials are required to be registered using JavaScript. Many template pre-compilers or loaders will handle this for you, calling Handlebars.registerPartial(). Finally, partials have to be separated from the templates where they’re being used. This can be a boon if your templates are large, but can also make it difficult for developers to fully understand the output of a template. They’ll need to switch between many different files before understanding the full output.

All these issues shape the way developers use partials. They end up being reserved just for the largest chunks of reusable code.

With Inline Partials, Handlebars finally releases the true potential of Partials, enabling you to drop JavaScript and the necessity to split partials into separate files. Inline Partials are defined inside your templates, in Handlebars syntax. There is no JavaScript required to register them. You just declare a partial and use it. In addition, they aren’t global but block-scoped. This means that once you’ve declared an Inline Partial in your template, it can only be used in the current scope and any below it.

Continue reading %Using Inline Partials and Decorators with Handlebars 4.0%