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:
- Supports dynamic code
- Produces HTML
- Follows DRY principle and focuses on reusability.
Basic Features of Jade(Pug)
- Tags
- Attributes
- 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
- JavaScript
- Loops
- Mixins
- 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:
- Supports Dynamic code
- Follows DRY principle
- Compiles Jade to HTML
Demerits of Jade:
One mistake in indentation of code or one missed whitespace results in a different output.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Kiran Joshi
Kiran is a Frontend developer and have knowledge of HTML5, SASS, Bootstrap, and Javascript. She has working knowledge of ReactJs as well.