JavaScript UI library Webix allows redefining the appearance of many elements through templating. For example, in tree view we can define the look of item through the following template:
view:"tree", data:tree_data,
template:"{common.icon()} #value#"
});
Here you can see the two main components of webix templates: common helpers and property placeholders. Common helpers are predefined pieces of logic which renders some common elements (tree icon in the above case). Property placeholders are markers that will be replaced with data from related data object.
By using html tags in the template we can change the look of component in many ways.
view:"tree", data:tree_data,
template:"{common.icon()} <button>#value#</button>"
});
or
view:"tree", data:tree_data,
template:"{common.icon()} {common.checkbox()} <i>#value#</i>"
});
Still we are limited. The above syntax doesn’t provide a way to define logic, e.g., loops, conditions, etc. We can define a template as a function but this soultion is not so elegant as it could be.
Why Handlebars
Handlebars is a free semantic web template system based on Mustache. It provides web developers with the ability to build semantic templates advantageously with no frustration.
There are quite a lot of template engines. But Handlebars has simple and at the same time powerful syntax that is available on many platforms. So if you master them, this knowledge may be reused in other projects.
Best of the Two Worlds
To use Handlebars, firstly you need to include the Handlebars library on the page.
src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0-alpha.2/handlebars.min.js">
</script>
Now you can use Handlebars templates instead of Webix templates like in the following piece of code:
view:"list",
data:list_data,
template:Handlebars.compile(" {{value}} <sup>By Handlebars</sup>")
});
So far it hasn’t differed a lot from Webix templates. Lets look at a slightly more complex example:
{{#each films}}
<h4><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h4>
<div>Released in {{year}}, Rating: {{rating}}</div>
{{/each}}
</script>
template:Handlebars.compile($("#list-template").html()),
data:{ films: grid_data }
});
Here we have placed the code of the template in a separate html tag, and just referenced the content of that tag while describing UI. The template in tag contains a loop for each item in the collection of films and some html formatting.
And even more
There are a lot of things which can be done with Webix UI and Handlebars, we’ve shown you only a small part of them.
Webix template is good for simple customizations. If you want to have more complex templating logic you can use Handlebars templates with Webix UI. The results will impress you.