Jade HTML Template Engine

In the last post I mentioned that when you start using Express, you are nudged towards Jade to create your HTML.

At its simplest, Jade provides a way to make your HTML more terse. To produce HTML like this:

We would only need to enter Jade like this:

We can break up the contents of our pages, so in this example the head contents are defined in a different file and can be shared across multiple pages. The syntax is very simple, indentation is used to nest elements within each other and you can add ID, class and other attributes with simple markup.

But really the power is that you can also do simple scripting inside the Jade file. So you can conditionally load chunks of the page based on data that you pass into the page. And then you can also pass in variables to the Jade template to be used when building the HTML. In the example above, the title is passed into the page as a variable from the route configuration.

Of course you can bind field onto your database using similar techniques. 

The structure of my real world application has a layout Jade file which itself is made up of several Jade files: head, header, footer, and foot. In the head I have all of my CSS and web attributes. The header is the navigation header for the site. The footer is a static footer navigation bar and the foot contains all of the JavaScript files that need to be downloaded to the client. In between header and footer I can insert my content.

The momentum in the web development world is very much towards AngularJS at the moment which doesn’t really sit with Jade too well. It is possible to use both but they tread on each others toes rather a lot so it may end up being more trouble than it’s worth. But for my purposes Jade and jQuery are working well together for me at the moment.