Friday, December 23, 2011

Using hogan.js with express on node.js

Thought i'd try getting twitter's hogan.js up and running with express... not as straight forward as i expected. Drawing upon this article on using mustache.js with express.js i created a simple adapter to help bridge functionality.

I would only use this while connect 3.x is in dev. After that i'd use TJ's consolidate.js cause i'm no TJ.

If you're looking for a full, working example, be sure to checkout a Nodestrap-- a repo i use as a project "prototype." It comes out of the box with better than average architecture, hogan-express templating, bootstrap 1.x. Its a good jumping off point.

Here's the adapter:

var HoganExpressAdapter=(function(){
var init=function(hogan) {
var compile=function(source){
return function(options) {
return hogan.compile(source).render(options);
};
}
return {compile:compile};
};
return {init:init};
}());
if(typeof module!== 'undefined' && module.exports){
module.exports=HoganExpressAdapter;
} else if (typeof exports!=='undefined') {
exports.HoganExpressAdapter=HoganExpressAdapter;
}

Here's an example of it in use:

var express=require('express'),
hogan=require('hogan.js'),
adapter=require('./hogan-express.js'),
app = express.createServer();
app.configure(function(){
app.use(express.static(__dirname + '/public'));
app.use(express.logger());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(app.router);
app.use(express.errorHandler({dumpExceptions:true,showStack:true}));
app.set('view engine','hogan.js');
app.set('view options',{layout:false});
app.set('views',__dirname+ '/views');
app.register('hogan.js',adapter.init(hogan));
});
app.get("/",function(req,res,next) {
res.render("index",{name:"micah"});
});
app.listen(8080);

In the views directory i have a index.hogan.js file-- that's the template.

It's worked for simple uses so far. I'll update if needs be.

6 comments:

  1. you could do this much simpler even for 2x, but with 3x coming out soon I wont go into details

    ReplyDelete
  2. Is there a specific syntax needed in the layout file to get layout:true to work?

    ReplyDelete
  3. Does the adapter need to be used somewhere, I'm not sure if this works as-is?

    What version of express is this for ?

    ReplyDelete
  4. It was express 2.x. Given that this code is > 6 months old, perhaps it is dead at this point!

    You may want to check out consolidate.js https://github.com/visionmedia/consolidate.js

    ReplyDelete
  5. I'd check out mmm.

    https://github.com/techhead/mmm

    It has support for layout, partials, and caching. It was made specifically for Express 3.

    ReplyDelete