4

I like the minimal-ness of mustache-style templating languages - I'm currently using mustache and icanhasmustache, but I've also checked out handlebars and hogan.

However I have a need to for an 'extends' type functionality, to allow a child to reference a particular parent template. I can't find documentation on how extends are implemented in any of the above, but I've seen (from random githib gists) that other people seem to be doing it.

Note: I'm aware of the existence of includes (sometimes called partials), however these seems to be for a parent to reference a particular child. That's the opposite of what I'm looking for - the child template in this case is the real 'base' document, the parent merely incidental, so I want the child to control the relationship.

mikemaccana
  • 81,787
  • 73
  • 317
  • 396
  • Maybe this will help (faking template extend in mustache.js) http://stackoverflow.com/questions/7925931/can-mustache-templates-do-template-extension – WTK Mar 07 '12 at 11:01
  • @WTK Thanks. I've seen that answer - mustache itself doesn't do it. My question is perhaps: does anything else? Using a static function per #2 in the ticked answer means you'd need a function for each parent. – mikemaccana Mar 07 '12 at 11:07

3 Answers3

8

2016 answer:

If you're using express, the layout middleware takes a layout option which you may find useful.

res.render('page', { layout: 'mylayout.jade' })

original answer: Very few JS libraries implement 'extends'-type functionality.

  • Nun is very mustache like, but server only (and no longer maintained)
  • Swig has extends, but isn't very mustache like.
  • Jade has extends and works in the browser, but isn't mustache like

I settled on Dust.JS, as it uses mustache-like sections, works on client and server, and supports overriding blocks on the parent from the child, giving effective extends support.

See the dust documentation, 'Blocks and Inline Partials' section:

{>base_template/}
{<title}
  Child Title
{/title}
{<main}
  Child Content
{/main}

Overriding the 'title' and 'main' sections from the parent template, keeping the surrounding contents.

mikemaccana
  • 81,787
  • 73
  • 317
  • 396
5

I'm looking into Nunjucks, which promises to fix some issues as well as support inheritance.

EDIT:

I have indeed adopted Nunjucks, it's pretty solid so far. One limitation I've encountered is that you can't specify multiple folders for precompiling, but I wrote a script to allow it.

Aram Kocharyan
  • 19,179
  • 11
  • 69
  • 93
2

Twitter's implementation of Mustache, Hogan, seems to support inheritance now.

See this recent commit: Hogan 3. Add template inheritance...

KajMagnus
  • 10,177
  • 14
  • 69
  • 115