Skip to content

Instantly share code, notes, and snippets.

@aackerman
Created March 30, 2012 01:53
Show Gist options
  • Save aackerman/2245723 to your computer and use it in GitHub Desktop.
Save aackerman/2245723 to your computer and use it in GitHub Desktop.
Express view adapter for Hogan.js
'use strict';
var fs = require('fs'),
path = require('path'),
hogan = require('hogan');
var adapter = (function() {
var dir = 'templates',
partials_dir = dir + '/partials',
extension = '.hogan',
partials = {},
html, layout;
//cache partials
var files = fs.readdirSync(partials_dir);
files.forEach(function(file){
var str = fs.readFileSync(path.join(partials_dir, file), 'UTF-8');
partials[path.basename(file, extension)] = hogan.compile(str);
});
//cache layout
var layout_dir = path.join(dir, 'layout' + extension);
if(path.existsSync(layout_dir)){
var str = fs.readFileSync(layout_dir, 'UTF-8');
layout = hogan.compile(str);
}
var compile = function(name) {
return function (options) {
var html = hogan.compile(name).render(options);
//if we want a layout yield the requested template with a layout
if ( layout && options.layout !== false && options.settings['use layout'] !== false) {
options['yield'] = html;
html = layout.render(options, partials);
}
return html;
};
}
return {compile : compile};
})();
module.exports = adapter;
var express = require('express');
var adapter = require('hogan-adapter.js');
var app = express.createServer();
app.register('hogan', adapter);
app.set('views', __dirname + '/templates');
app.set('view engine', 'hogan');
app.get('/', function(req, res){
res.render('index');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment