Last active
May 28, 2016 07:09
-
-
Save acstll/5023658 to your computer and use it in GitHub Desktop.
Use lodash templates with Express 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var fs = require('fs'); | |
var _ = require('lodash'); | |
var cache = Object.create(null); | |
exports.renderFile = function (path, options, callback) { | |
var html; | |
var template; | |
var context = options || {}; | |
if (cache[path]) { | |
html = cache[path](context); | |
return callback(null, html); | |
} | |
fs.readFile(path, 'utf8', function (err, data) { | |
if (err) return callback(err); | |
try { | |
template = _.template(data); | |
} catch(err) { | |
return callback(err); | |
} | |
cache[path] = template; | |
html = template(context); | |
callback(null, html); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment