Friday, October 25, 2013

Quick and Dirty Server Side Select Helper for Handlebars,js

Handlebars.js is one of  my favorite templating engines. One of the biggest reason for that is because it is usable both on the client and server sides.  While the client-side is pretty familiar, the server-side has its challenges, not the least of which is there is no DOM. Having no DOM means that some convenient methods like createElement don't exist, but there are times when being able to deliver a ready render HTML page is important. 

In one of my projects, we wanted to do server-side rendering of an edit page. Nothing tricky or flashy, just send the user the data they entered previously for editing. This kind of a page is easy with just about every templating engine around. One problem HTML element is the select tag, because it is a composite element consisting of <select> enclosing one or more <option> tags. Luckily handlebars.js includes the ability create your own helpers, which are bits of code you write yourself and handlerbars invokes. Writing a select helpers is pretty easy on the client since you have access to the DOM. Most client-side helpers will generate the select and each of the options including their value and selected attributes. 

I initially was trying to go this route on the server-side as well. And then I stopped myself. The lack of DOM access caused the code to quickly get more complicated than I liked. So I decided to go another way. Instead of rendering out the select element, I instead decide to render the attributes of the option element. This way my helper is much simpler. To use it simply add:

{{option <value of option> <current value>}}

to each option element. The helper will render out the value attribute and if it is the currently selected option, the selected attribute as well.

I may change my mind and render the entire select element, but for now I like this simpler approach.