Jade Node.js Template Engine, Filters & Mixins
In my previous post I have talked about conditional statements inside of jade. In this post I will write about filters and mixins in jade template engine.
Filters
Filters in jade means something different from what you may know as filters like the ones in Angular.js. In Jade filters allow you to use different languages (text formatters) with jade template. (e.g CSS, CoffeeScript, markdown, etc), and all filters are compile time, thus they does not support dynamic content.
For example to use markdown we would first install markdown
1 |
npm install markdown |
Now if we wish to use markdown in our jade template, we can simply use the :markdown syntax, Note: all filters use the colon “:” syntax, eg. (:sass, :less, :coffee, etc)
1 2 3 4 5 6 7 8 9 10 |
#content :markdown ## This is a markdown H2 tag with two hash [I'm an inline-style link with title](https://www.google.com "Google's Homepage") //HTML output <div id="content"> <h2>This is a markdown H2 tag with two hash</h2> <a href="https://www.google.com" title="Google's Homepage">I'm an inline-style link with title</a> </div> |
Mixins
Mixins allow one to use reusable code blocks in jade. The way to declare mixins is by the keyword mixins following the tags that you wish to display, example
1 2 3 4 5 |
mixin myFancyList ul li a li b li c |
In order to use the mixin we just need to append it with the “+” sign
1 |
+myFancyList |
Mixin can also take arguments like function
1 2 3 4 5 6 7 8 |
mixin bullet(name) li= name //usage ul bullet('a') bullet('b') bullet('c') |
One can also use conditional statement and blocks of jade inside of mixins, the indent statement below the calling of the mixin is taken as the blocl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
mixin blog_post(title) h2= title if block block else p There is no content for this blog yet //usage +blog_post('hello world') //output <h2>hello world</h2> <p>There is no content for this blog yet</p> //usage +blog_post('hello world with content') p This is a hello world post //output <h2>hello world with content</h2> <p>This is a hello world post</p> |
In my next and probably last blog post on jade, I will talk about includes in jade and template inheritance.
Leave A Comment