http://www.developer.com/lang/jscript/build-express.js-web-applications-faster-with-jade-and-stylus.html

Back to article

Build Express.js Web Applications Faster with Jade and Stylus


November 10, 2011

If I had a dollar for every hour spent over the past 15 years agonizing over HTML and CSS, my Developer.com articles would be filed from a penthouse balcony in San Juan. Paradoxically, the almost manic obsession with constantly tweaking Web layouts seems to be particularly prevalent among those who tend to experience the most frustration in doing so, namely developers lacking refined design skills. Falling squarely into this crowd, the process of sorting through seemingly countless DIVs, classes, selectors, and inheritances has always seemed an exercise in insanity, one which stood out in stark contrast to my highly organized coding environment.

These frustrations largely vanished when I began working with Node.js a few months ago. Although still relatively nascent, the Node.js community has really seemed adept at acknowledging the Web's past successes and failures, creating a powerful ecosystem of technologies which collectively contribute to a highly productive development environment. Among these contributions are the Jade templating engine and Stylus CSS preprocessor. I like to think of Jade and Stylus as HTML and CSS done right, particularly for developers who prefer a somewhat more structured environment.

Introducing Jade

The Jade templating engine is one of many Node.js-related projects created and maintained by the apparently insomnia-stricken developer TJ Holowaychuk. Based upon the ideas of HAML, another popular templating engine which seeks to introduce clarity into the HTML development process, Jade relies upon a blend of indentation, intuitive syntactical shortcuts, and the introduction of just enough logic to produce even the most sophisticated HTML layouts. Consider for instance the following Jade template:

!!! 5
html
head
title Tailgating Recipes
body
div#container
h1 Turkey Chili
ul.recipe
li 1 pound turkey
li Tomato sauce

Rendered using Jade, the above template will produce the following HTML:

<!DOCTYPE html>
<html>
<head>
<title>Tailgating Recipes</title>
</head>
<body>
<div id="container">
<h1>Turkey Chili</h1>
<ul class="recipe">
<li>1 pound turkey</li>
<li>Tomato sauce</li>
</ul>
</div>
</body>
</html>

A quick glance at the source and output should be enough for most developers to conclude which syntax is more enjoyable to write.

Using Jade with Express

Although Jade was created with Node.js in mind, a number of ports have already been made, including for PHP, Ruby, and Scala. I'd imagine the majority of readers would like to know more about Jade's Node-specific applicability, and so I will demonstrate how to go about integrating it into the Express Node.js framework. Presuming you've already installed Node.js and Express, install Jade using the Node Package Manager:

$ npm install jade

Although I'm jumping ahead a bit, go ahead and install Stylus as well, since we'll be talking about it later in this article:

$ npm install stylus

Next, create a new Express application, adding Jade and Stylus support:

$ express -t jade -c stylus

Express will create a Jade template (views/layout.jade) and home page view (views/index.jade). Open up the layout.jade file and you'll see the following markup:

!!!
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body!= body

The title= title and body!= body declarations are Express' way of determining where a view variable should be inserted, and where the view should be inserted into the layout, respectively, but everything else you otherwise see is Jade-specific. Try tinkering with the layout.jade and index.jade markup, using the many examples found in the Jade README as the basis for experimentation.

Iterating Over Dynamic Data with Jade

One feature which tends to confuse many Jade beginners pertains to how dynamic data can be embedded into a Jade template. Using Express, this task is actually pretty easy. As an example, modify the index route, passing along an array containing various tailgating recipes:

app.get('/', function(req, res){
res.render('index', {
title: 'Tailgating Recipes',
recipes: ['Turkey Chili', 'Jalapeno Poppers', 'Fudge Brownies']
});
});

Within the corresponding index.jade view, you can use Jade's each iterator to iterate over each array:

h1= title
p Welcome to #{title}

ul
each recipe in recipes
li= recipe

It's that simple!

Embedding JavaScript

You'll almost certainly want to embed client-side JavaScript into an Express/Jade-driven application, and in doing so, pass variables from your Express application into the JavaScript. I had a bit of trouble figuring this out when first starting out with Express and Jade, and so wanted to provide an example for others potentially experiencing similar issues. All that is required is for you to properly indent the code below the script declaration. For instance, I use the following snippet within an Express-driven Web application which incorporates the Google Maps API:

 script 
var latlng = new google.maps.LatLng(#{latitude}, #{longitude});
var myOptions = {
zoom: 15,
center: latlng,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};

var map = new google.maps.Map(document.getElementById("map"), myOptions);

var markerPoint = new google.maps.LatLng(#{latitude}, #{longitude});

var marker = new google.maps.Marker({
position: markerPoint,
map: map,
title: "#{name}"
});

Introducing Stylus CSS Preprocessor

With Jade so adeptly handling the HTML-related responsibilities, it's time to introduce some CSS into the project. But given the fantastically structured environment Jade brings to the table, it would be a real shame to resort to old school style sheets. Enter Stylus, a CSS preprocessor sporting a syntax similar to Jade, and additionally a number of impressive features which greatly enhance CSS maintainability.

In the previous section I showed you how to install Stylus, so I'll presume you've already done so and just forge ahead with an introduction to key features. Looking back to Express' default Jade template, you'll find the following line:

link(rel='stylesheet', href='/stylesheets/style.css')

Rendered to the browser, this line produces:

<link rel="stylesheet" href="/stylesheets/style.css"/>

This should look quite familiar to any developer with even a rudimentary understanding of CSS. But it's here where the similarities begin to tail off. Navigate to the application's /public/stylesheets directory and you'll find two files: style.css and style.styl. Open the style.css file and you'll find typical CSS syntax:

body {
padding: 50px;
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;
}
a {
color: #00b7ff;
}

This CSS is generated by Stylus by way of the styles.styl file! Open the styles.styl file and you'll see the following code:

body
padding: 50px
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif
a
color: #00B7FF

Notice how the Stylus syntax eschews brackets in favor of indentation, and does away with semicolons altogether? This is just a small sampling of the succinctness Stylus has to offer. For instance, one of my favorite features is the ability to use variables within the .styl file. Modify styles.styl to look like this:

link-color = #00B7FF

body
padding: 50px
font: 14px "Lucida Grande", Helvetica, Arial, sans-serif
a
color: link-color

In this example, I've created a variable named link-color, and later used that variable within the a declaration's color attribute! This feature gives you the opportunity to manage all values which are potentially used within multiple locations of your style sheet. Simply reloading the application within your browser will cause the styles.css file to be updated.

Conditional Statements within CSS

Another great Stylus feature is the ability to use conditional statements within the style sheet. For instance, suppose you were in the midst of developing a new website and wanted an easy way to debug your style sheet. Using Stylus, you can create a variable named for instance debug, and then check that value throughout the stylesheet in order to set certain properties accordingly:

debug = true

...

if debug
div
border 1px solid black

These two features alone are enough to make the case for adopting Stylus for a future project, and I've hardly scratched the surface! Be sure to check out the Stylus documentation for a complete list of examples.

Conclusion

Are you using Jade or Stylus in a current project? Tell us about your experiences in the comments!

About the Author

Jason Gilmore is founder of the publishing, training, and consulting firm WJGilmore.com. He is the author of several popular books, including "Easy PHP Websites with the Zend Framework", "Easy PayPal with PHP", and "Beginning PHP and MySQL, Fourth Edition". Follow him on Twitter at @wjgilmore.

Sitemap | Contact Us