I always end up implementing some convoluted JavaScript inside a Handlebars helper whenever I have to render lists with any depth. Think trees — there could be several nested lists. I don't like the JavaScript approach I've taken in the past, I'm using Handlebars to generate dynamic markup — it should be able to handle nested lists, right? My preferred approach these days is to use a partial template, and to call that recursively.
Wednesday, March 5, 2014
Wednesday, February 5, 2014
Handlebars: Overriding Global Partials
The HandlebarsJS API let's you register partial templates — templates that get rendered within the context of a larger template — in a global scope. These partials are available to all other templates. For example, if there's a section of markup repeated throughout many of your templates, rather than repeat yourself, you could compose a partial template. You would then make this available to all other templates by using the registerPartial()
function. This helps simplify larger templates too, by breaking them down into smaller, more manageable parts. However, if you're using the same global partial in all your templates, you're probably going to run into a situation where you need to swap the default partial for something more specific. Let's say one of your pages requires a custom header partial. We can pass in a custom partial that's used in that context only.
Thursday, January 23, 2014
Handlebars Helpers vs String Utilities
The Handlebars client-side template system let's the developer register new template helpers. In effect, this extends the template syntax, adding to the short list of available helpers. The decision to include as few helpers as possible in the package was an intentional one - there's no sense including a lot of stuff that nobody uses. Especially when it's easy enough to make your own using registerHelper(). For this reason, only the bare essentials such as if
and each
are available out of the box. But is there an alternative approach to formatting your template data?