Jade Node.js Template Engine, Include & Template Inheritance Part 6

In this post, I will write about using includes and template inheritance in Jade template engine.
You can also check out my previous 5 post on Jade.

  • Jade Node.js Template Engine Part 1
  • Jade Node.js Template Engine Basics Syntax Part 2
  • Jade Node.js Template Engine DataBinding Part 3
  • Jade Node.js Template Engine, Conditional Logic Statements Part 4
  • Jade Node.js Template Engine, Filters & Mixins Part 5
  • Includes (aka partial views for .net developers)

    To include css, javascript, html file, one can use the include directive in Jade. Lets say, you have a css that you wish to include in your jade file, you can then use the include like below, include can also import any html file that you may, or even markup text.

    One thing to note is the scope in the parent file and the include file is shared, so it allows one to use variables inside the include that are defined outside. Also one has to use the right extension for the file with the correct path. The example above shows the data/copyright.html is an html file located in the data folder.

    There are also some other ways to include, css and javascript code blocks in Jade.

    Template Inheritance

    Most sites have a generic look and feel, and if you are using includes (partials) it could soon become very ugly and hard to maintain all the includes. This is where Jade provides us with template inheritance, using the Block keyword as placeholders to inject other templates into the view.

    We may have already seen this if we have used express web engine the layout.jade file as show below

    In order to use this layout file, Jade provides us with the keyword extends, for example in our index.jade file we can extend the layout like.

    From the above example, we see that we are replacing content, but Jade also provides us with prepend and append to the blocks. For example, if we wish to add zepto.js to our layout we can use the append keyword.

    Or if we want to prepend a css file to the link tag, so that style2.css loads before style.css we can use the prepend keyword.

    Note: Conditional statements like if else do not work with blocks since they are evaluated during compile time. The code below does not work.

    Summary

    This marks the end of the Jade, node.js template engine series, if you have any questions feel free to contact me, in the upcoming post I will write more about node and grunt/gulp (the Javascript task runner/ stream building system).

    Sign up and follow my mail list if you wish to be posted on upcoming blog post.