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.
{{x-sort-by list=friends property="name" as |sorted|}}
{{#each sorted as |friend|}}
…
{{/each}}
{{/x-sort-by}}
import Ember from 'ember';
/**
* use "{{yield sorted}}" as handlebars template
*/
export default Ember.Component.extend({
list: undefined,
property: undefined,
sorted: function () {
const list = this.get("list");
if (!list) {
return [];
}
return list.sort((a, b) => {
const x = this._getValue(a);
const y = this._getValue(b);
return (x < y) ? -1 : (x > y) ? 1 : 0;
});
}.property("list", "property"),
_getValue(x) {
const property = this.get("property");
const value = property === null ? x : x[property];
if ((typeof value) === "string") {
return value.toLocaleLowerCase();
} else {
return value;
}
}
});
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.