Jade Mixins & Includes
The latest release of Jade 0.13.0 adds mixins and includes. Jade users have longed for some method of static include, so it’s (finally) here, and compliments mixins nicely, allowing you to store mixins in one or more separate files.
Mixins
A mixin definition takes the form mixin <name> [( params )] block, where params is identical to JavaScript function params, simply a list, as it’s converted to a JavaScript function within Jade to become part of the output function.
Using a mixin is identical to the definition, however omitting the block. Mixins allow you to encapsulate repeated chunks of a template, such as form fields as shown in the following snippet. This example has a local variable user passed to the template with the properties { name: '...', email: '...' }, which is then accessible throughout any mixins defined without explicitly passing it (though you may if you like).
mixin field(type, name, label)
.field(class='field-' + type)
label #{label}:
input(type=type, name='user[#{name}]', value=user[name])
form
mixin field('text', 'name', 'Username')
mixin field('text', 'email', 'Email')
mixin field('password', 'pass', 'Password')
input(type='submit', value='Sign Up')
Outputting:
<form>
<div class="field field-text">
<label>Username:</label>
<input type="text" name="user[name]" value="TJ Holowaychuk"/>
</div>
<div class="field field-text">
<label>Email:</label>
<input type="text" name="user[email]" value="tj@learnboost.com"/>
</div>
<div class="field field-password">
<label>Password:</label>
<input type="password" name="user[pass]"/>
</div>
<input type="submit" value="Sign Up"/>
</form>
Includes
The include <path> directive signals Jade to read and parse the file, then return it’s root node (a block), injecting it into the calling template, as if it were written in the same file. The <path> given is relative to the dirname of the calling template, which is exposed to Jade via the filename option, which is populated by jade.renderFile() and Express, otherwise you need to supply this.
For example our mixin(s) could live in ./mixins, and our previous example could look something like below:
include mixins/form-helpers
form
mixin field('text', 'name', 'Username')
mixin field('text', 'email', 'Email')
mixin field('password', 'pass', 'Password')
input(type='submit', value='Sign Up')
Or the classic header / footer example, first index.jade:
html
include includes/head
body
h1 My Site
p Welcome to my super lame site.
include includes/foot
includes/foot.jade:
#footer
p Copyright (c) foobar
includes/head.jade:
head
title My Site
script(src='/javascripts/jquery.js')
script(src='/javascripts/app.js')
That’s all for now, hopefully I’ll have some time in the near future to clean things up and get 1.0 (finally again :)) out the door.