Wednesday, February 17, 2016

A Jade Tutorial for Beginners

Jade is an elegant templating engine, primary 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:

[code language="html"]
<div>
<h1>Ocean's Eleven</h1>
<ul>
<li>Comedy</li>
<li>Thriller</li>
</ul>
<p>Danny Ocean and his eleven accomplices plan to rob
three Las Vegas casinos simultaneously.</p>
</div>
[/code]

This is what the same markup looks like in Jade:

[code language="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.
[/code]

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.

[author_more]

The Basics

I’m going to highlight three basic features in Jade

  • Simple tags
  • Adding attributes to the tags
  • Blocks of text

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.

[code language="jade"]
div
p Hello!
p World!
[/code]

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

[code language="html"]
<div>
<p>Hello!</p>
<p>World!</p>
</div>
[/code]

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.

View this example on CodePen

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.

[code language="jade"]
div(class="movie-card", id="oceans-11")
h1(class="movie-title") Ocean's 11
img(src="/img/oceans-11.png", class="movie-poster")
ul(class="genre-list")
li Comedy
li Thriller
[/code]

Pretty neat right?

[code language="html"]
<div class="movie-card" id="oceans-11">
<h1 class="movie-title">Ocean's 11</h1>
<img src="/img/oceans-11.png" class="movie-poster">
<ul class="genre-list">
<li>Comedy</li>
<li>Thriller</li>
</ul>
</div>
[/code]

View this example on CodePen

Continue reading %A Jade Tutorial for Beginners%


by Sanjay Guruprasad via SitePoint

No comments:

Post a Comment