Jade nested mixins

Hello everyone!

If you are a frontend developer and you are using gulp/grunt/webpack with the template engine like Jade,  it is very a likely that you face with a problem like – how to create mixin with mixin inside.

In other words, you need to set mixin with your random name and display it inside your parent mixin in the particular place. It seems like a javascript object with methods which would be called in loop by their names.

You can do it in Jade with the code like this:


//- global object for nested mixins

- blocks = {}

//- mixin for set other mixin into global object for nested mixins

mixin set(key)

- blocks[key] = this.block

mixin container-for-content

.container

//- It needs for declaring place where nested mixis will displayed.

block

.blocks
  //- Runs loop for iterates each block in global blocks object and runs "render" function
  each element, i in blocks
  = blocks[i]()

Now you can use this construction like this:

+container-for-content
 +set('first-block')
   .first-row
     | First row
 +set('second-block')
    .second-row
     | Second row

And as a result you should get output like this:

<div class="first-row">First row</div>
<div class="second-row">Second row</div>