a short introduction to jade


jade is a template engine for node.js and the default rendering engine for the express web framework.


simple jade how-to

  1. change your texteditor of choice to use 2 spaces for tabs (!)
  2. npm install express
  3. npm install jade
  4. cd /to/your/working/directory
  5. mkdir views
  6. create a file views/layout.jade
    !!! 5
      html(lang='en')  
        head  
      title= title  
      body!= body  
        div#navigation!= partial('navigation.jade')  
      
    
    
    
    • jade uses text intend (2 spaces) to determine where an HTML element belongs in the DOM
    • !!! 5 -> use the HTML 5 doctype declaration
    • html(lang='en') -> the dom element html has the attribute language set to 'en'
    • title= title -> the dom element titel has the text node set to the (=) escaped value of the variable 'title'
    • body!= body -> render into the body dom element the (!=) un-escaped value of the variable 'body'
    • div#navigation!= partial('navigation.jade') -> render the jade template views/navigation.jade (a partial) into the div dom element with the id 'navigation'

  7. create a file views/index.jade
    h1 
      a(href='http://www.franz-enzenhofer.com/') Franz Enzenhofer
    
    
  8. create a file views/navigation.jade
    div#navigation
      a(href='/') home
    
    
  9. glueing it together - create a file server.js
    //create an app server
    var app = require('express').createServer();
    //set path to the views (template) directory
    app.set('views', __dirname + '/views');
    //set path to static files
    app.use(express.static(__dirname + '/../public'));
    //handle GET requests on /
    app.get('/', function(req, res){res.render('index.jade', {title: 'Franz Enzenhofer'});});
    //listen on localhost:3000
    app.listen(3000);
    
  10. node server.js
  11. visit http://127.0.0.1:3000/
  12. understand the magic
    • the object passed as second arguement to the res.render function is a global variable in the rendered templates and partials.
    • the rendered output of the passed template (in this case index.jade) is available as the 'body' variable in the layout.json

further reading