All Articles

Discover Jade, a great template engine for Node

Jade is a powerful tool that makes writing HTML easier than ever. We use it extensively in our project and wanted to share our experience.

Jade logo

What is Jade ?

Jade is a robust, elegant, feature rich template engine for nodejs.

— Jade documentation

A web template engine is a tool that allow developers to write simpler HTML, while adding some nice features that quickly become essential. These templates are then rendered in standard, W3C-compliant HTML and are completely transparent to your users.

What does it look like ?

As a simple example, this :

doctype html
html(lang="en")
    head
        title Shawt !
    body
        h1 Home page
        ul#menu
            li.menuitem Item 1
            li.menuitem Item 2
            li.menuitem Item 3

is rendered as :

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Shawt !</title>
  </head>
  <body>
    <h1>Home page</h1>
    <ul id="menu">
      <li class="menuitem">Item 1</li>
      <li class="menuitem">Item 2</li>
      <li class="menuitem">Item 3</li>
    </ul>
  </body>
</html>

What about those features ?

Jade adds some essential features to HTML, such as conditionals, loops, and mixins.

Conditionals

- var user = { name: 'John' }
if user
    div.welcomebox
          // Filtered inline output
          p.
              Welcome, #{user.name}
else
    div.loginbox
        form(name="login", action="/login", method="post")
              input(type="text", name="user")
              input(type="password", name="pass")
              input(type="submit", value="login")

is rendered as :

<div class="welcomebox">
  <!-- Filtered inline output-->
  <p>Welcome, John</p>
</div>

Loops

ul
    each val in [1, 2, 3, 4, 5]
        li= val

is rendered as :

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Mixins

Mixins allow developers to create snippets to reduce redundancy and increase code reusability.

//- Declaration
mixin list
    ul
        li foo
        li bar
        li baz
//- Use
+list()
+list()

is rendered as :

<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>
<ul>
  <li>foo</li>
  <li>bar</li>
  <li>baz</li>
</ul>

Great then, how do I get it ?

Jade is a great, simple tool that gives more freedom to web developers to build what they want, the way they want. We highly recommend you to try it :)

You can visit the official website here, or install Jade through npm via npm install jade.

Hope this helps !

Originally published on Svbtle.