X

Jade Node.js Template Engine, Filters & Mixins Part 5

Jade

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

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)

#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

This is a markdown H2 tag with two hash

I'm an inline-style link with title

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

mixin myFancyList
   ul
     li a
     li b
     li c

In order to use the mixin we just need to append it with the “+” sign

+myFancyList

Mixin can also take arguments like function

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

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

hello world

There is no content for this blog yet

//usage +blog_post('hello world with content') p This is a hello world post //output

hello world with content

This is a hello world post

In my next and probably last blog post on jade, I will talk about includes in jade and template inheritance.

Taswar Bhatti:
Related Post