Search code examples
javascriptnode.jsswig-template

template inheritance from multiple sub-templates


So i have a website, it's structure is consisted of various templates:

- index //the html skeleton, with script tags and css links
- header //the header of the page
- topnavigation //contains the main nav with the menu
- content //this is where the dynamic content will be changed for different pages
- footer //the footer

Right now, the only way i know to integrate this is:

res.render(content);    
content -> inherits footer
footer -> inherits topnavigation
topnavigation-> inherits header
header -> inherits index

I think it would be much more practical and easy to maintain if i could have something like:

res.render(content);
content -> inherits dochead
index -> includes header + topnnavigation + footer
  • Am I wrong?
  • If i'm right, how can i do this?

Thanks


Solution

  • Typical extends setup is something more like this: (for a working example, you can see how the Swig documentation sets up its layouts here: https://github.com/paularmstrong/swig/tree/master/docs/layouts)

    • skeleton.html html skeleton with blocks:
      • {% block html %}
      • {% block css %}
      • {% block js %}
      • {% block body %}
    • base.html extends skeleton.html, base layout with blocks/sub-blocks:
      • {% block body %}
        • {% block header %} Includes some default header content.
          • {% block nav %} Includes the main navigation content.
        • {% block content %} Empty
        • {% block footer %} Includes copyright, etc.
    • index.html extends base.html
      • {% block nav %} (content for navigation, potentially, otherwise just let base.html render its nav content
      • You'll override any other blocks set up in base.html here as needed as well. If you find yourself needing more control over the template, consider creating another sub-layout that extends base.html and then having index.html extend that instead.