node.jsexpresstemplatesmustache

How can I exclude or specify an alternate layout.mustache for one of my views in Node.js?


Currently all pages are rendered from a views/layout.mustache file and a page-specific views/page.mustache template

I want to use an alternate layout.mustache and/or skip the layout.mustache all-together when rendering a certain view within my application. What is the ideal way to go about doing this?

Here's a snippet of my app.configure:

app.configure(function(){
    ...
    app.set('views', __dirname + '/views');
    app.register(".mustache", require('stache'));
    ...
});

Solution

  • Which version of express are you using? With v3.0 the concept of layouts was removed.

    V3.0 introduces the concept of blocks. I don't use mustache but an example with jade looks like this:

    // my-template.jade
    extends my-layout
    
    block head
      script(src="myfile.js")
    
    block content
      h1 My page
    

    and

    // my-layout.jade
    doctype 5
    html
      head
        title My title
        block head
      body
        #content
          block content
    

    With extends you can choose whatever "parent" layout you want. An overview of supported template engines is in the express wiki.

    In express versions before 3.0 you could specify the layout when rendering

    res.render('index', {
      title : 'Page with distinct layout', 
      layout : 'layout.mustache'
    });
    

    or disable layouts for certain views

    res.render('start', {
      title : 'Page without layout', 
      layout : false
    });