Ryan Padget

Web Development. Simplicity. Creativity.

Client-Side Jade

Posted by Ryan Padget on January 29, 2012 Comments

Jade is an elegant solution to templating and works great on the server combined with Express, but what if you want to use it on the client with a framework like Backbone? Here is a method I have used with success that depends on Stitch:

Server-Side:

// require dependencies
var express = require('express');
var stitch = require('stitch');
var app = module.exports = express.createServer();
var package;
// configure express to use stylus middleware
app.configure(function(){
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(require('stylus').middleware({ src: __dirname + '/public' }));
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});
// stitch files together for browser
package = stitch.createPackage({
  paths: [__dirname + '/public/app'], // directory with files to stitch
  compilers: {
    jade: function(module, filename)  {
      var jade = require('jade');
      var source = require('fs').readFileSync(filename, 'utf8');
      source = "module.exports = " + jade.compile(source, {compileDebug : false, client: true}) + ";";
      module._compile(source, filename);
    }
  }
});
// serve stitched files with express from specific path
app.get('/javascripts/application.js', package.createServer());

Client-Side:

// include script https://raw.github.com/visionmedia/jade/master/runtime.js
// include script /javascripts/application.js
var template = require('templates/hello'); // p Hello, #{name}
var context = {name: "World!"};
var content = template(context); // Hello, World!
// or
require('templates/hello')({name: "World!"});