var Q = require('q'); var fs = require('fs'); var path = require('path'); var glob = require('glob'); var stringify = require('json-to-html'); var Liquid = require('liquid-node'); /** * Define any custom liquid filters here. */ var filters = { /** * Return a string formatted version of a JSON object. * Useful for quick debugging of template data. */ prettify: function(obj) { try { return '
' + stringify(obj) + ''; } catch (e) { return 'Error prettifying'; } }, /** * Serialize Javascript objects into a JSON string */ stringify: function(obj) { try { return JSON.stringify(obj); } catch (e) { return 'Error stringifying'; } }, }; /** * Manages templates. Only supports Mustache currently/ */ function OKTemplateRepo(options) { options = options || {}; var root = this._root = options.root || 'templates'; var ext = 'liquid'; var cache = this._cache = {}; var engine = this._engine = new Liquid.Engine; engine.registerFilters(filters); engine.fileSystem = new Liquid.LocalFileSystem(root, ext); this._populateCache(engine, cache, ext); } 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(engine, cache, ext) { var self = this; var files = glob.sync(this._root + '/*.' + ext); files.forEach(function eachFile(file) { var name = path.basename(file, '.' + ext); var templateString = fs.readFileSync(file, {encoding: 'UTF8'}); cache[name] = { name: name, templateString: templateString, render: function(data) { return Q.promise(function(resolve, reject) { // TODO Not sure if this caches parsed templates behind the scenes? engine.parseAndRender(templateString, data) .then(resolve) .catch(reject); }); } } }); } module.exports = OKTemplateRepo;