Introduction To JADE Template Engine

Posted By Kiran Joshi | 30-Dec-2018

A template engine allows us to inject data and then converts it into HTML.

 

Jade is a template engine also known as pug is used for Node.JS. The primary use of Jade is it's a server-side templating. Jade syntax is easy to learn and remember. Jade has many advantages if compared to plain HTML such as:

  1.  Supports dynamic code
  2.  Produces HTML 
  3.  Follows DRY principle and focuses on reusability.

Basic Features of Jade(Pug) 

  1. Tags
  2. Attributes
  3. Block of code

1. Tags: 

  • Tags are very easy to use, no brackets required to cover tag.
  • Every tag used is a self-closing tag in Jade so no closing tags are required which minimises a lot of code.
  • Jade uses whitespaces and indentation to define nesting of tags. So the indentation and whitespaces play a crucial role in Jade.

 2. Attributes:    

  • Attributes can be added to the tag inside the closed brackets.
  • Similar to CSS selectors, here dot(.)  is used for a Class attribute as a prefix and use hash(#) for an ID attribute.

3. Block of Text:

  • Jade always treats the first word of every line as an HTML element.
  • When using a p tag for a large block of text use a period(.) after the tag which indicates that all the code after that period(.) is text and Jade stops treating the first word of each line as an HTML element. 

Advanced Features of Jade

  1. JavaScript 
  2. Loops 
  3. Mixins
  4. Interpolation 

1. JavaScript:  By starting a line with hyphen we declare that the code is written in javascript. 

2. Loops: Jade provides a for loop and each loop so we won't rely on the javascript looping structure.

  

3. Mixins: Mixins are defined using mixin keyword and are used as a function which takes arguments and returns a markup. 

	mixin profilePic(url, alternateText)
	  div.profilePic
	    img(src="/images/#{url}.png")
   
	+profilePic("bg1", "Image not available")
   

4. Interpolation: Binding a variable with a string in JS becomes annoying. Jade offers a simplified and an elegant solution for it. 

	- var fName = "John Doe";

	div
	  h1 Hello, #{fName}!
   

Merits of Jade: 

  1. Supports Dynamic code
  2. Follows DRY principle
  3. Compiles Jade to HTML

Demerits of Jade:

One mistake in indentation of code or one missed whitespace results in a different output.

Request for Proposal

Recaptcha is required.

Sending message..