Faster Web Development Using the Jade Template Language

0
7419

Web visual

You can build Web pages faster with the Jade template language. Jade is an elegant and efficient way to do HTML coding. Old HTML files can be easily converted to Jade.

Jade template language is a major milestone in Web development. It helps developers think of modular, reusable sections of Web pages or apps. So it means less time spent and fewer key strokes. It may take a day or two to get comfortable with this new style, but once you are comfortable, you will never go back to traditional HTML coding.
Tim Berners-Lee, the man who invented the Web, never thought that Web pages would be hand coded using the machine friendly HTML (markup language). With the introduction of Wiki and blog editors, people can publish content on the web without learning HTML. But this does not solve the challenges that Web and app developers face with HTML. We still need to hand code each page.
Mastering HTML involves a steep learning curve. HTML is more browser-friendly than human-friendly, with its tags, attributes, angular brackets and DOM structure. These severely impact readability and maintainability. In addition, HTML has its own idiosyncrasies. Various types of elements are treated differently—in some cases, the closing tag is optional; while for others, there is no closing tag. With new revisions to HTML, what was mandatory earlier has become optional subsequently (refer to ‘The HTML Syntax’ in the References section). Though templating languages like Jade do not eliminate all the difficulties in learning and using HTML, they are a major step towards faster Web development.
Inline page templating languages like PHP and JSP have been around for a while. They too achieve the same result as the new templating languages. But the latter do their job elegantly with a strong philosophy behind them. Jade has been inspired by another template language called HAML.
The Jade templating engine is not only for HTML page development, but also for other markup languages like XML.
This article contains many practical tips and examples not available in online documentation.

Figure 1
Figure 1: Using Cloud editor jsbin.com

The Jade philosophy
Jade shares the same philosophy as HAML:

  • Markup should be beautiful
  • Markup should be DRY (Don’t Repeat Yourself)
  • Markup should be well indented
  • The HTML structure should be clear

Snippet 1 gives an example of a basic HTML page with the title, heading and paragraph.

Table 1
Snippet 1: Your first ‘Hello, Jade’ program

This example is so clear that you might be tempted to skip the remainder of this article. Don’t! There is even more power in Jade!

Why learn Jade?
There are many reasons to learn Jade. It significantly improves the speed at which Web pages are produced. Besides, it also eases the overall maintenance of HTML pages because the code is more readable.
Jade includes programmatic constructs for decisions (if-else) and looping. It also has support for variables and substitution. This is the basic feature of a template language.
There are often one or more sections of HTML pages in a site that get repeated across multiple HTML files. Jade makes sharing easy with sections like headers and footers in one file, and can easily insert them in many pages which share the same content using features like include and inheritance.
Jade is whitespace sensitive language, which means that indentation, which is done for better readability, defines a block. For instance, in the code shown in Snippet 1, h1 (heading) and p (paragraph) are indented. This tells Jade that it is a new block and defines the boundary of the body (<body>).
In a literal sense, the overall keystrokes required to code a page of HTML are reduced in Jade. Typing of ‘<’ and ‘>’ for opening tags and closing tags is not required. This also eliminates the possibility of errors caused by the wrong placement of matching tags.
Jade is the default template engine in the Node Express framework. It is written in and generates JavaScript output, which goes well with the trend of ‘JavaScript everywhere’.

Installation and set-up

Using a Cloud editor
The simplest way to try Jade without the hassle of any installation is via a browser, using an online Cloud editor. JSbin is an online IDE for Web programming. Visit http://jsbin.com and select ‘Jade’ in the HTML window (Figure 1).

Setting up Jade on your computer
In the first place, you should have npm (node package manager) already installed on your computer. For installation of Node.js and npm, please refer to the OSFY article, ‘Developing Applications Using Node.js’ published in the October 2013 issue. To install Jade from the command line, type:

$ npm install jade --global

To check if the installation is complete, use the following command:

$ jade --version

The version used at the time of writing this article is 1.9.2.

Getting started
Type Snippet 1 into a file and name it hello.jade. Ensure that your editor does not have ‘tab to spaces’ conversion. Let each indent be a tab. Make sure about this since it is most important.
From the directory where hello.jade is located, type the commands below to generate your HTML file:

$ jade -P . // dot at end of command is for current directory
$ jade -P hello.jade // convert one file to HTML

This will generate a file hello.html.
It’s important to note that you should not open a .jade file in a browser. You should only open the .html generated file in a browser to check the output. If you are using an online IDE (like jsbin.com), you can see a live preview.
The very first line of HTML is the doctype. Jade has many shorthand notations that eliminate the need to remember long text or switch between files to copy text. These are listed in Table 1.

Table
Table 1

For more doctypes, refer to online documentation
(see References).

More HTML elements
The example given in Figure 2 has more HTML elements than a simple ‘Hello world’ program.

Figure 2
Figure 2: An example with more HTML elements

Variables and iterators

A templating language cannot be complete without variables and control structures. Given below is an example of a common page that can generate two different HTML pages — one for Bollywood actors and another for the movies. You could also generate one page combining actors and their movies.

- var page = {‘title’: ‘Bollywood’, ‘heading’: ‘Bollywood Home’};
- var actors = [‘Shah Rukh’, ‘Aamir’,’Kareena’, ‘Kangana’];
- var movies = [‘Ra.One’, ‘3 Idiots’, ‘Jab We Met’, ‘Queen’];
- var about = ‘movies’;
- var list = ((about == ‘actors’)? actors:movies);
doctype html
html
title #{page.title}

body
h1 #{page.heading}
p This page is all about #{about}.
h2 All our #{about}
ul
li #{list[0]}
li #{list[1]}
li #{list[2]}
li #{list[3]}
footer &copy Copyright 2015 Janardan Revuru

The given example is self-explanatory. Here are a few key points to note. Line 5 has the ternary operator used to switch between pages —Actors or Movies. Variable substitution happens with #{variable}.

Iterators
In Snippet 2, lines 15 to 18 can be replaced by the iterator feature of Jade. This eliminates repetition of list item tags equal to the number of list elements. Jade also has a ‘while’ iterator for conditional looping.

each val in list
li= val
Figure 3
Figure 3: The ooutput of snippet 2

Jade command line options

In Snippet 2, we have variables page.title, page.header and about inside the file. We can also pass them as command line parameters. With this, you can generate different pages with different content.
From Snippet 2, remove lines 1 and 4 where we declare variables. From the command line, pass it as an object. Jade also takes a JSON file name, which contains an object instead of a JSON string.

$ jade -P -O ‘{“page” :{“title”:”Bollywood”,”heading”:”Bollywood Home”}, “about”:”actors”}’ var.jade

Other important command line options are:

-P --pretty compile pretty html output
-p --path <path> filename used to resolve includes
-O --obj <path|str> JavaScript options object or JSON file containing it
-o --out <dir> output the compiled html to <dir>.

This avoids mixing of Jade files with HTML files. You can have a whole directory watched.

-w --watch watch files for changes and automatically re-render.
Table 2
Table 2

Jade tips for newbies

Jade is space and tab sensitive. Configure your editor to have either spaces or tabs, but they should not be mixed in the same file. For example, if you copy code from a browser to an editor, it is possible that you have a mix of tabs and spaces in your file. The Jade file interpreter will fail with errors. This is the most common mistake made by beginners.
Every first string in a Jade file is converted to an HTML tag. In the first of the three examples given in Table 2 above, a custom tag <Delhi> is created. This tag is not created in the second example because there is a ‘.’ (dot) after p (paragraph tag). Also remember that Jade does not recognise HTML tags. A typo in an HTML tag will create a new tag, as shown in the third example.
Remember that no file should start with an indent, and the first line’s first character should not be space.
You can convert your existing HTML files to Jade using the online tool. This helps you get familiar with Jade faster.

Other features
This article covers just a basic introduction to Jade. There are advanced features like inheritance, mixins, include, etc. You need to be familiar with the inheritance concept to understand Jade in Node Express auto generated files. Look for the online references for these features.

References
[1] http://jade-lang.com/ Official Homepage and documentation
[2] http://www.w3.org/TR/html5/syntax.html
(8 HTML Syntax – W3C)
[3] http://naltatis.github.io/jade-syntax-docs/ -> Jade Playground; Try here first
[4] http://jade-lang.com/reference/doctype/ -> More doc types
[5] http://jade-lang.com/reference/attributes/
[6] http://www.learnjade.com/ -> Best Jade tour and tutorial. Better than official Jade homepage
[7] http://html2jade.aaron-powell.com/

LEAVE A REPLY

Please enter your comment!
Please enter your name here