Separating the concerns in JavaScript with HandleBars templating
‘Separation of concerns’, ‘Abstraction’, ‘MVC’ call it what you will, the isolation of logic and presentation in modern software architecture drives homes all the benefits it promises. Our recent discovery of the logic-less template engine, Handlebars JS, has led to a swifter and tidier approach to developing JavaScript clients here at Dottedeyes.
The premise of this nifty JavaScript library is that you create your desired HTML template, either inline or in a separate file, then with a simple call to the Handlerbars.compiler you inject your model into the template (JSON works best). This results in a fully populated HTML object that can be placed where you like in your main page using JQuery – so no more HTML\JavaScript string meshing!
The Handlebars syntax is chiefly based around the {{ }} notation (“handlebars moustache”, get it?). By placing the field names from your model, inside the curly braces, you get a populated model-view object. The extent and dimension of your model can be as complex as it needs to be – Handlebars provide ‘Blocks’ for iterating through lists, and you can navigate up and down your data graph using ‘.’ notation.
It really is a ‘logic-less’ engine. The creators of Handlebars have clearly set out to ensure absolutely no logic sits in your HTML – this doesn’t mean Handlebars is dumb – if you find the need to add logic around displaying certain portions of your presentation based on data being present or of a certain range etc. you have the ability to write your own logic and register it in a custom helper. Our example: test POSTCODE to see if it was MAPPED or UNMAPPED, if it was display a nice <href> link to an Openlayers map, if not then do not display that HTML tag.
If you find your Javascript codebase becoming bloated with yucky ‘HTML-Javascript’ concatenations, or find it awkward to build a complex view of your data by having to carefully stitch JSON into HTML strings, then HandlebarsJS is the solution to look at. It’s simple, lightweight and allows you to separate all those concerns between your domain model and how you want to present it. Find out more at http://handlebarsjs.com/
Written by Martin Roddy, Senior Software Engineer at Dotted Eyes, 20th August 2013