A Jade Tutorial for Beginners

Jade is an elegant templating engine, primarily used for server-side templating in NodeJS. In plain words, Jade gives you a powerful new way to write markup, with a number of advantages over plain HTML.

For example, take a look at this movie card in HTML:

div> h1>Ocean's Elevenh1> ul> li>Comedyli> li>Thrillerli> ul> p>Danny Ocean and his eleven accomplices plan to rob three Las Vegas casinos simultaneously.p> div>

This is what the same markup looks like in Jade:

div h1 Ocean's Eleven ul li Comedy li Thriller p. Danny Ocean and his eleven accomplices plan to rob three Las Vegas casinos simultaneously.

The Jade version is elegant and concise. But it’s not just about the beautiful syntax. Jade has some really neat features, allowing you to write modular and reusable markup. Before we get into these powerful features, let’s do a quick overview of the basics.

The Basics

I’m going to highlight three basic features in Jade

If you want to try this out as we go along, you can use CodePen and choose Jade as your HTML preprocessor or use the online compiler on the official Jade page to compile your Jade to HTML.

Simple Tags

As you might have noticed earlier, there are no “closing” tags in Jade. Instead, Jade uses indentation (i.e. white space) to determine how tags are nested.

div p Hello! p World!

In the example above, since the paragraph tags are indented, they will end up inside the div tag. Simple!

div> p>Hello!p> p>World!p> div>

Jade compiles this accurately by treating the first word on each line as a tag, while subsequent words on that line are treated as text inside the tag.

Attributes

All this is great, but how do we add attributes to our tags? Quite simple really. Let’s go back to our first example and toss in some classes and a poster image.

div(class="movie-card", ) h1(class="movie-title") Ocean's 11 img(src="https://www.sitepoint.com/img/oceans-11.png", ) ul(class="genre-list") li Comedy li Thriller

Pretty neat right?

div class="movie-card" id="oceans-11"> h1 class="movie-title">Ocean's 11h1> img src="/img/oceans-11.png" class="movie-poster"> ul class="genre-list"> li>Comedyli> li>Thrillerli> ul> div>

But it doesn’t stop here. Jade provides special shorthand for IDs and classes, further simplifying our markup using a familiar notation:

div.movie-card#oceans-11 h1.movie-title Ocean's 11 img.movie-poster(src="https://www.sitepoint.com/img/oceans-11.png") ul.genre-list li Comedy li Thriller

As you can see, Jade uses the same syntax as that which we’re already familiar with when writing CSS selectors, making it even easier to spot classes.

Blocks of Text

Let’s say you have a paragraph tag and you want to place a large block of text in it. Jade treats the first word of every line as an HTML tag – so what do you do?

You might have noticed an innocent period in the first code example in this article. Adding a period (full stop) after your tag indicates that everything inside that tag is text and Jade stops treating the first word on each line as an HTML tag.

div p How are you? p. I'm fine thank you. And you? I heard you fell into a lake? That's rather unfortunate. I hate it when my shoes get wet.

And just to drive home the point, if I were to remove the period after the p tag in this example, the compiled HTML would treat the “I” in the word “I’m” as an opening tag (in this case, it would be the tag).

Powerful Features

Now that we’ve covered the basics, let’s take a peek at some powerful features that will make your markup smarter. We’ll look at the following features in remainder of this tutorial:

Using JavaScript in Jade

Jade is implemented with JavaScript, so it’s super-easy to use JavaScript in Jade. Here’s an example.

- var x = 5; div ul - for (var i=1; i

What did we just do here?! By starting a line with a hyphen, we indicate to the Jade compiler that we want to start using JavaScript and it just works as we would expect. Here’s what you get when you compile the Jade code above to HTML:

div> ul> li>Helloli> li>Helloli> li>Helloli> li>Helloli> li>Helloli> ul> div>

We use a hyphen when the code doesn’t directly add output. If we want to use JavaScript to output something in Jade, we use = . Let’s tweak the code above to show a serial number.

- var x = 5; div ul - for (var i=1; i

And voilà, we now have serial numbers:

div> ul> li>1. Helloli> li>2. Helloli> li>3. Helloli> li>4. Helloli> li>5. Helloli> ul> div>

Of course, in this case, an ordered list would be much more appropriate, but you get the point. Now, if you’re worried about XSS and HTML escaping, read the docs for more info.

Loops

Jade provides an excellent looping syntax so that you don’t need to resort to JavaScript. Let’s loop over an array:

- var droids = ["R2D2", "C3PO", "BB8"]; div h1 Famous Droids from Star Wars for name in droids div.card h2= name

And this will compile as follows:

div> h1>Famous Droids from Star Warsh1> div class="card"> h2>R2D2h2> div> div class="card"> h2>C3POh2> div> div class="card"> h2>BB8h2> div> div>

You can iterate over objects and use while loops too. Check out the docs for more.

Interpolation

It can get annoying to mix JavaScript into text like this p= "Hi there, " + profileName + ". How are you doing?" . Does Jade have an elegant solution for this? You bet.

- var profileName = "Danny Ocean"; div p Hi there, #. How are you doing?

Mixins

Mixins are like functions. They take parameters as input and give markup as output. Mixins are defined using the mixin keyword.

mixin thumbnail(imageName, caption) div.thumbnail img(src="https://www.sitepoint.com/img/#%3CimageName%3E.jpg") h4.image-caption= caption

Once the mixin is defined, you can call the mixin with the + syntax.

+thumbnail("oceans-eleven", "Danny Ocean makes an elevator pitch.") +thumbnail("pirates", "Introducing Captain Jack Sparrow!")

Which will output HTML like this:

div class="thumbnail"> img src="/img/oceans-eleven.jpg"> h4 class="image-caption"> Danny Ocean makes an elevator pitch. h4> div> div class="thumbnail"> img src="/img/pirates.jpg"> h4 class="image-caption"> Introducing Captain Jack Sparrow! h4> div>

Putting It All Together

Let’s put together everything we’ve learned so far. Say we have a nice array of movies, with each item containing the movie’s title, the cast (a sub-array), the rating, the genre, a link to the IMDB page and the image path for the movie’s poster. The array will look something like this (white space added for readability):

- var movieList = [ < title: "Ocean's Eleven", cast: ["Julia Roberts", "George Clooney", "Brad Pitt", "Andy Garcia"], genres: ["Comedy", "Thriller"], posterImage: "/img/oceans-eleven", imdbURL: "http://www.imdb.com/title/tt0240772/", rating: 7 >// etc. ];

We have 10 movies and we want to build nice movie cards for each of them. Initially, we don’t plan to use the IMDB link. If a movie is rated above 5, we give it a thumbs up, otherwise, we give it a thumbs down. We’ll use all the nice features of Jade to write some modular code to do the following:

  1. Create a mixin for a movie card
  2. Iterate through the movie list and use the mixin to create one card per movie.

So let’s create the mixin first.

mixin movie-card(movie) div.movie-card h2.movie-title= movie.title img.movie-poster(src=movie.posterImage) h3 Cast ul.cast each actor in movie.cast li= actor div.rating if movie.rating > 5 img(src="https://www.sitepoint.com/jade-tutorial-for-beginners/img/thumbs-up") else img(src="https://www.sitepoint.com/jade-tutorial-for-beginners/img/thumbs-down") ul.genre each genre in movie.genres li= genre

There’s a lot going on up there, but I’m sure it looks familiar – we’ve covered all this in this tutorial. Now, we just need to use our mixin in a loop:

for movie in movieList +movie-card(movie)

That’s it. Is that elegant or what? Here’s the final code.

- var movieList = [ < title: "Ocean's Eleven", cast: ["Julia Roberts", "George Clooney", "Brad Pitt", "Andy Garcia"], genres: ["Comedy", "Thriller"], posterImage: "/img/oceans-eleven", imdbURL: "http://www.imdb.com/title/tt0240772/", rating: 9.2 >, < title: "Pirates of the Caribbean", cast: ["Johnny Depp", "Keira Knightley", "Orlando Bloom"], genres: ["Adventure", "Comedy"], posterImage: "/img/pirates-caribbean", imdbURL: "http://www.imdb.com/title/tt0325980/", rating: 9.7 >]; mixin movie-card(movie) div.movie-card h2.movie-title= movie.title img.movie-poster(src=movie.posterImage) h3 Cast ul.cast each actor in movie.cast li= actor div.rating if movie.rating > 5 img(src="https://www.sitepoint.com/jade-tutorial-for-beginners/img/thumbs-up") else img(src="https://www.sitepoint.com/jade-tutorial-for-beginners/img/thumbs-down") ul.genre each genre in movie.genres li= genre for movie in movieList +movie-card(movie)

And here’s the compiled HTML:

div class="movie-card"> h2 class="movie-title">Ocean's Elevenh2> img src="/img/oceans-eleven" class="movie-poster"/> h3>Casth3> ul class="cast"> li>Julia Robertsli> li>George Clooneyli> li>Brad Pittli> li>Andy Garciali> ul> div class="rating"> img src="img/thumbs-up"/> div> ul class="genre"> li>Comedyli> li>Thrillerli> ul> div> div class="movie-card"> h2 class="movie-title">Pirates of the Carribeanh2> img src="/img/pirates-caribbean" class="movie-poster"/> h3>Casth3> ul class="cast"> li>Johnny Deppli> li>Keira Knightleyli> li>Orlando Bloomli> ul> div class="rating"> img src="img/thumbs-up"/> div> ul class="genre"> li>Adventureli> li>Comedyli> ul> div>

But wait a minute. What if we now want to go to the movie’s IMDB page when we click on a movie’s title? We can add one line: a(href=movie.imdbURL) to the mixin.

mixin movie-card(movie) div.movie-card a(href=movie.imdbURL) h2.movie-title= movie.title img.movie-poster(src=movie.posterImage) h3 Cast ul.cast each actor in movie.cast li= actor div.rating if movie.rating > 5 img(src="https://www.sitepoint.com/jade-tutorial-for-beginners/img/thumbs-up") else img(src="https://www.sitepoint.com/jade-tutorial-for-beginners/img/thumbs-down") ul.genre each genre in movie.genres li= genre

Conclusion

We went from knowing nothing about Jade to building some beautiful modular movie cards. There’s a lot more to Jade, but I’ve glossed over some concepts to keep things simple. So I hope this tutorial piqued your curiosity to learn more.

Important note: As some of you might already know, Jade has been renamed to Pug due to a software trademark claim. In the future, articles on Jade will use the new name “Pug” or “PugJS”.

Frequently Asked Questions (FAQs) about Jade Tutorial for Beginners

What is Jade and why is it important in web development?

Jade, also known as Pug, is a high-performance template engine heavily influenced by Haml and implemented with JavaScript for Node.js and browsers. It provides a clean, elegant syntax that allows developers to write HTML templates in a much more concise way. Jade is important in web development because it reduces the amount of time spent writing HTML code, making the development process more efficient. It also supports dynamic code, which means you can include variables and expressions that get evaluated while rendering the HTML.

How do I install Jade?

To install Jade, you need to have Node.js and npm (Node Package Manager) installed on your computer. Once you have these, you can install Jade globally on your system by running the command npm install jade -g in your terminal or command prompt. This will allow you to use Jade from any directory on your computer.

How do I convert HTML to Jade?

Converting HTML to Jade can be done manually or using online tools like html2jade.org. To do it manually, you need to understand the Jade syntax and how it maps to HTML. For example, HTML tags become Jade elements, HTML attributes become Jade attributes, and so forth. Online tools can automate this process, but it’s still important to understand the underlying conversion rules.

What are the main differences between Jade and HTML?

The main differences between Jade and HTML lie in their syntax. Jade uses indentation to represent nested elements and doesn’t require closing tags, making it more concise than HTML. However, HTML is more widely used and understood, and some developers find its explicit closing tags and lack of indentation rules easier to read and understand.

How do I use variables in Jade?

Variables in Jade can be defined using the - syntax. For example, - var title = 'Home' defines a variable named title with the value ‘Home’. You can then use this variable in your Jade template by prefixing it with #<> . For example, h1= title would render as

Home

in HTML.

Can I use JavaScript in Jade templates?

Yes, you can use JavaScript in Jade templates. Jade supports a variety of JavaScript constructs, including variables, expressions, control structures (like if-else statements and for loops), and functions. To include JavaScript code in your Jade template, prefix it with - .

How do I include partials in Jade?

Partials, or reusable chunks of Jade code, can be included in other Jade templates using the include keyword. For example, include header would include the contents of the header.jade file at that point in the template.

How do I comment in Jade?

Comments in Jade can be added using // . For example, // This is a comment would add a comment to your Jade code. Note that this comment will not be included in the rendered HTML.

How do I format text in Jade?

Text in Jade can be formatted using HTML-like tags. For example, p This is some text would render as

This is some text

in HTML. You can also use Markdown syntax in Jade by prefixing your text with :markdown .

How do I handle errors in Jade?

Errors in Jade can be handled using try-catch blocks in your JavaScript code. When an error occurs while rendering a Jade template, Jade will throw an exception that you can catch and handle appropriately.

Sanjay Guruprasad

Sanjay loves architecting systems and runs the web and mobile team at Softrade. He also likes to hack on tiny visualization and machine learning projects. You can learn more about him and his projects at sanjaypojo.com.