Search code examples
pug

How render a block depending on a variable? PUG (JADE)


First time working with pug.

The situation is such that all pages use the same header and footer.

main-layout.pug:

<header>
   h1 Some text
   h2 Second text
</header>
    
<footer>
   h3 Third text
</footer>

But on one page, I need to change half of the header, and leave the rest unchanged:

<header>
   h1 Some text
     div
      span Span text
</header>

<footer>
   h3 Third text
</footer>

How can i do this?

The final page has a name map.pug and only has main page inheritance.

map.pug:

extends ../layouts/main-layout

Solution

  • Split it in several files e.g. with a version suffix. A parent file (header.pug) points to several childs and decides by a passed variable or takes the default (header-v1.pug) when nothing is given.

    |-- partials
    |-- |-- footer.pug
    |-- |-- footer-v1.pug
    |-- |-- footer-v2.pug
    |-- |-- header.pug
    |-- |-- header-v1.pug
    |-- |-- header-v2.pug
    |-- |-- header-v3.pug
    |-- default.pug
    |-- main-layout.pug |-- map.pug

    main-layout.pug

    //- doctype, meta, etc ...
    
    include partials/header
    
    block content
    
    include partials/footer-v1
    

    header.pug

    if headerVersion === "v2"
        include header-v2
    else if headerVersion === "v3"
        include header-v3
    else
        include header-v1
    

    header-v1.pug

    header
       h1 Some text
       h2 Second text
    

    header-v2.pug

    header
       h1 Some text
         div
          span Span text
    

    The render call can pass the headerVersion variable:

    return res.render('default.pug', {
        // nothing specifed: v1 is taken as default
    });
    
    return res.render('map.pug', {
        headerVersion: 'v2'
    });