Recipes

Usage multiple blocks

Multiple blocks are in Pug not allowed, see the issue. But, using the mixin block we can simulate multiple blocks.

//- 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]()

In your mixin you can use many block mixins by a block name, for example:

mixin article
  i Article demo
  ul.article
    li
      +block('article1')
    li
      +block('article2')

Define named blocks before using of your mixin:

+block('article1')
  p Content of article 1

+block('article2')
  p Content of article 2

+article()

Output

Article demo
  • Content of article 1

  • Content of article 2

Usage dynamic mixins

Create the dynamic mixin to simplify usage syntax:

mixin mixin(name)
  +#{name}()

Now you can call a mixin by name:

mixin a
  p Mixin A

mixin b
  p Mixin B

-
  let someCondition = -1;
  let myMixin = someCondition > 0 ? 'a' : 'b'

+mixin(myMixin)

Output

Mixin B