var fs = require('fs'); var path = require('path'); var glob = require('glob'); var stringify = require('json-to-html'); var LiquidEngine = require('liquid-node').Engine; var liquid = new LiquidEngine(); /** * Add any custom liquid filters here. */ liquid.registerFilters({ /** * Return a string formatted version of a JSON object. * Useful for quick debugging of template data. */ stringify: function(obj) { try { return '
' + stringify(obj) + ''; } catch (e) { return ''; } } }); /** * Manages templates. Only supports Mustache currently/ */ function OKTemplateRepo(options) { options = options || {}; this._root = options.root || 'templates'; this._extPattern = options.ext || '.+(liquid|html)'; this._cache = {}; this._populateCache(this._cache); } OKTemplateRepo.prototype.getTemplate = function getTemplate(name) { return this._cache[name]; } /** * Go through our template dir and read the template files * into memory as strings. * Assumes all templates fit into memory. */ OKTemplateRepo.prototype._populateCache = function _populateCache(cache) { var self = this; var files = glob.sync(this._root + '/*' + this._extPattern); files.forEach(function eachFile(file) { var ext = path.extname(file); var name = path.basename(file, ext); var templateString = fs.readFileSync(file, {encoding: 'UTF8'}); cache[name] = { name: name, templateString: templateString, render: function(data) { // TODO Not sure if this caches parsed templates behind the scenes? return liquid.parseAndRender(templateString, data); } } }); } module.exports = OKTemplateRepo;