Question

I'm using twitter's Hogan.js implementation of the Mustache templating language. What is the < tag for?

You can see reference to the tag in compiler.js line 341:

'<': function(node, context) {
      var ctx = {partials: {}, code: '', subs: {}, inPartial: true};
      Hogan.walk(node.nodes, ctx);
      var template = context.partials[createPartial(node, context)];
      template.subs = ctx.subs;
      template.partials = ctx.partials;
    },

There aren't many comments around this section, and I can't figure it out.

If I use the < tag in my template, what will it do?

Was it helpful?

Solution

After much Googling I found the answer, it's a clever template inheritance method (just what I was hoping it was).

I found this issue & accompanying gist, it explains the problem and their suggested solution. It seems this functionality has been implemented in hogan.js, but is not part of the official Mustache spec yet.

This functionality doesn't work with the currently published version on npm (2.0.0), instead you need to use version 3.0.0 from github. Version 2 just treats < & > the same.


Example:

Main template (template.html):

<html>
    <head>
        <title>{{$title}}Default Title{{/title}}</title>
    </head>
    <body>
        {{$content}}<p>Default Content</p>{{/content}}
    </body>
</html>

Content template (content.html):

{{<template}}
    {{$title}}Override title{{/title}}
    {{$content}}
        <div>
            <h1>Override Content</h1>
        </div>
        {{>anotherPartial}}
    {{/content}}
{{/template}}

Now all you need to do is render content.html, and it will be included in template.html as follows:

<html>
    <head>
        <title>Override title</title>
    </head>
    <body>
        <div>
            <h1>Override Content</h1>
        </div>
        {{>anotherPartial}}
    </body>
</html>

Note the usage of $ tags which are replaced by the same tags in content.html.

This functionality makes it really easy to render views in multiple formats, perhaps for different devices. It also removes the need for dynamic partial names (as many people want).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top