Let’s look at the ordinary
#each block helper in Handlebars.js first. If we compile the following simple template:
Then we can execute it like so:
Using Handlebars Partials
What if we had the following model:
Here, each person has an array of friends, and each friend has their own array of friends. Suppose we’d like to render these relationships as an HTML unordered list:
This will require recursion.
We can combine the
#each block helper with partial templates. When we have the partial template call itself, then we have recursion. A partial template for a person looks like this:
And our main template is:
Using a Recursion Helper
We’ll keep the same model, but we would like to render a different output this time:
In order to render the pluses, our Handlebars templates needs to know what the recursion depth is at any given time, and we don’t have access to this information when using the
#each block helper and a partial. However, we can still solve this by creating our own custom helper:
(Note that the custom helper returns a Handlebars SafeString to prevent Handlebars from HTML escaping the names of the people, should they contain escapable characters.)
This custom helper takes a person object and a recursion depth level. By default, the depth level will be 1, resulting in one plus sign. The helper calls a partial, which renders one person (ignoring their friends). It then calls itself recursively for the person’s friends, increasing the recursion depth by 1.
Our main template becomes:
And our partial becomes:
This strategy allows us to implement recursion with depth level.