Home > Enterprise >  How to use a block inside an included file in PUG?
How to use a block inside an included file in PUG?

Time:05-30

I want to do something like this

//- page-a.pug
extends layout.pug

block scripts
  script(src='/jquery.js')
  script(src='/pets.js')

block content
    include ./layout2.pug
        block article1
            something something....
        block article2
            something something....

article1 and article2 are in the layout2.pug file

CodePudding user response:

Currently, multiple blocks in Pug are not allowed, see the issue.

But, using the mixin block we can simulate multiple blocks. For example:

index.pug

//- important to use `var`, not `let` or `const`
- var blocks = blocks || {}

mixin block(name)
  -
    if (this.block && !this.block.length)
      blocks[name] = this.block
    else if (!!blocks[name]) blocks[name]()

//- define your custom block with name `article1` 
 block('article1')
  p something something 1 ...

//- define your custom block with name `article2`
 block('article2')
  p something something 2 ...

//- use the `include` after block definitions
include article

article.pug

h2 Articles
ul
  li
    //- output block with name `article1`
     block('article1')
  li
    //- output block with name `article2`
     block('article2')

Generated HTML:

<h2>Articles</h2>
<ul>
  <li>
    <p>something something 1 ...</p>
  </li>
  <li>
    <p>something something 2 ...</p>
  </li>
</ul>
  • Related