Mixins
Mixins allow you to create reusable blocks of jade.
//- Declaration
mixin list
ul
li foo
li bar
li baz
//- Use
+list
+list
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
<ul>
<li>foo</li>
<li>bar</li>
<li>baz</li>
</ul>
They are compiled to functions and can take arguments:
mixin pet(name)
li.pet= name
ul
+pet('cat')
+pet('dog')
+pet('pig')
<ul>
<li class="pet">cat</li>
<li class="pet">dog</li>
<li class="pet">pig</li>
</ul>
Mixin Blocks
Mixins can also take a block of jade to act as the content:
mixin article(title)
.article
.article-wrapper
h1= title
if block
block
else
p No content provided
+article('Hello world')
+article('Hello world')
p This is my
p Amazing article
<div class="article">
<div class="article-wrapper">
<h1>Hello world</h1>
<p>No content provided</p>
</div>
</div>
<div class="article">
<div class="article-wrapper">
<h1>Hello world</h1>
<p>This is my</p>
<p>Amazing article</p>
</div>
</div>
Mixin Attributes
Mixins also get an implicit attributes argument taken from the attributes passed to the mixin:
mixin link(href, name)
//- attributes == {class: "btn"}
a(class!=attributes.class, href=href)= name
+link('/foo', 'foo')(class="btn")
<a href="/foo" class="btn" >foo</a>
Note
The values in
attributes
are already escaped so you should
use !=
to avoid escaping them a second time (see also unescaped attributes).
You can also use with &attributes
(see also &attributes)
mixin link(href, name)
a(href=href)&attributes(attributes)= name
+link('/foo', 'foo')(class="btn")
<a href="/foo" class="btn" >foo</a>
Rest Arguments
You can write mixins that take an unknown number of arguments using the "rest arguments" syntax. e.g.
mixin list(id, items)
ul(id=id)
each item in items
li= item
+list('my-list', 1, 2, 3, 4)
<ul id="my-list">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>