Functional Templates in Handlebarsby Christoph Dähne on 31.05.2016
Inspired by this nice Blog Post I used functional templates in one of our projects and immediately saw the following benefits:
- short and clear components and source files
- good separation of concerns: one component has only one task to do
- little effort to reuse functions and code
What are Functional Templates?
Functional Templates are Handlebars Helpers or EmberJs Components which do not render any output. They perform simple and independent side-tasks, e.g. they change the variables of the current scope of your template. At first that does not sound useful at all, but consider simple constructs like if-then-else or for-each – widely accepted and known to be very useful indeed.
Example in EmberJS: Sorting a list
Consider you have a few items to render in a bullet list – sorted of course. Sounds easy at first, but it is worth its own component for the following reasons:
- Sorting might be by value or by property
- If the value is a String, you want sorting by lower-cased value
- Values might be null or undefined
The following examples shows the usage and implementation of functional templates in handlebars.
Handlebars.java: Filtering a list
Depending on the library the Handlebar Helpers are implemented differently. The following example runs with the Handlebars.java port of Handlebars.