Handlebars is cool

tl;dr

Handlebars > other JS templating libs/tools (ps. maybe except dust.js)

Here’s the story

I work for startup GameBoxed.com. My job is to implement new game scenarios, improve old ones and few other things. All games are written in JavaScript/CoffeeScript, all of them are one screen only – every view change is made by JS. For few months we used to render all views on server-side (statically and dynamically), sometimes updating old static templates with new values with jQuery. It was quite clear to us we should change the way we render views – we should only use static, not prefilled templates with easy way to fill them with data. First try was Mustache, next is Handlebars. We’re also thinking about Pure.js, but this blog will show you, that Pure.js is hard.

Templating trash

Pros and cons of Handlebars

compilable

You don’t have to process same template on one runtime – Handlebars.compile simply creates function, which can be applied to context to render HTML.

extendable

Nice API to extend template logic, but with little pain, that makes you to think twice about putting logic into template.

simple

Create template with holes, fill them with JSON data, add to DOM with third-party tool.

only for render

It’s created for one thing only – rendering templates. There is no support for updating existing components. There is also no support for DOM management.

Why I like Handlebars.js over Pure.js

First of all it’s too complicated. You can pass your data (context) as crappy JSON with matchers as field names, or leave translating matchers in directives. Matchers seems to be hard to manage – for each piece of data you must define one, so your templates are not so friendly to get filled. Of course you can use conventions, so it can be easier, but than you have to use ugly css class-based convention. It is also too complicated to render template for collections.

Pure.js is much bigger than handlebars – in sense of functionality. It can manage DOM, update easily rendered view. Maybe it’s worth it to write matchers to get this ease of updating? I’m almost 100% sure, that it is easier to render template with Handlebars and than update it with jQuery – it’ll need some conventions, but much more flexible than those from pure.js. In next blog I will show how to write Handlebars templates that are easy to update.

Ps. While I was about to finish this blog post, Andrzej tweeted about dust.js in LinkedIn. Fuuuu…

  1. No comments yet.

  1. No trackbacks yet.