4 ms·
Handlebars (handlebarsjs.com) solves several of these issues: Items in lists don't have to be objects with fields; you can display primitives like strings and
by tomdale 15y ago
Handlebars (handlebarsjs.com) solves several of these issues:
Items in lists don't have to be objects with fields; you can display primitives like strings and numbers by using {{this}}:
{{#each tags}}
<li><a href="tags.html#{{this}}">{{this}}</a></li>
{{/each}}
Shadowing properties from parent context objects isn't a problem. Handlebars allows you to reach parent contexts with a '../' notation:
{{#each comments}}
<h2><a href="/posts/{{../permalink}}#{{id}}">{{title}}</a></h2>
<div>{{body}}</div>
{{/each}}
Regarding looping and conditional branching, Handlebars has an {{#if}} helper that does not evaluate to true for empty arrays:
{{#if authors}}
{{#each authors}}
{{firstName}} {{lastName}}
{{/each}}
{{else}}
No authors to display.
{{/if}}
I don't fully understand the complaint about recursive data structures. I usually just register a helper that can invoke itself recursively.
- wycats 15y agoIt's worth noting that #if, #each etc. are not built-in structures. They are simply helpers that you can register in the host language. Block helpers receive the block as a function that can be invoked as though it was a top-level template. Consider the simple #with helper: Handlebars.registerHelper('with', function(object, options) { // invoke the sub-template passed as a block to the with helper with the object parameter return options.fn(object); }); And its usage: {{#with person}} Name: {{name}} {{/with}} This means that you can build arbitrary control structures and iterators in the host language and expose them to Handlebars.