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
- change your texteditor of choice to use 2 spaces for tabs (!)
npm install expressnpm install jadecd /to/your/working/directorymkdir views- 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 declarationhtml(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'
- create a file
views/index.jadeh1 a(href='http://www.franz-enzenhofer.com/') Franz Enzenhofer
- create a file
views/navigation.jadediv#navigation a(href='/') home
- 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); node server.js- visit http://127.0.0.1:3000/
- 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