Jade

Jade is an HTML templating language that's extremely popular in Node circles. You make fewer keystrokes to get the same result, which makes you a more productive coder. This is very Node.

First Install with NPM

To use Jade you must install the package. Do this with NPM.

npm install jade

Here's a gulpfile:

var gulp = require('gulp');
var jade = require('gulp-jade');
var gutil = require('gulp-util');
var components = {
jade: './jade/**/*.jade',
out: './build'
}
gulp.task('jade', function() {
return gulp.src(components.jade)
.pipe(jade({pretty:true}))
.on('error', gutil.log)
.pipe(gulp.dest(components.out));
})
gulp.task('watch', function() {
gulp.watch(components.jade, ['jade']);
});

Elements

The first word on any line is the html element:

h1 Hello there

Compiles to:

<h1>Hello there</h1>

Nesting elements

We can nest elements inside each other using indentation:

article
h1 Hello
p Hey!

Compiles to:

<article>
<h1>Hello</h1>
<p>Hey!</h1>
</article>

Attributes

We can create attributes:

a(href='http://www.lolcats.com/') LOL cats

Compiles to:

<a href="http://www.lolcats.com/">Lol cats</a>

Variables

We can include variables in our template using an equals sign like this if we just have one value:

article
h1= titleContent

or using curly brace interpolation like this if we want to embed content into text:

html
head
title myWebsite.com - #{titleContent}

Compiling Jade

We con compile Jade manually using the jade package. First we install it with npm:

npm install jade

Now we can compile our template. This gives us a template function:

var jade = require('jade');
var template = jade.compile('h1 hello #{name}');

Or from a file:

var template = jade.compileFile('./path/to/template.jade');

Finally we can compile our template into HTML, passing it an object full of include variables, like so:

template({name: "Davie Skitch Mulldoon"});

Jade with Gulp

We can use gulp to automatically compile jade into static html templates.

We use the gulp-jade package

gulp.task('assets:templateCache', function () {
return gulp.src('../jade/**/*.jade')
.pipe(jade({basedir: __dirname}))
.on('error', gutil.log)
.pipe(gulp.dest('../build/templates'));
});

Angular Exercise

Create a gulp task to automatically compile a folder full of jade into a folder full of html.

Extension

Try to integrate gulp-template-cache to generate an angular template module from a folder full of jade.

comments powered by Disqus