/* * * Utils (hoganjs-utils.js) * Author: rtfpessoa * */ (function() { var fs = require('fs'); var path = require('path'); var hogan = require('hogan.js'); var hoganTemplates = require('./templates/diff2html-templates.js'); var extraTemplates; function HoganJsUtils(configuration) { this.config = configuration || {}; extraTemplates = this.config.templates || {}; var rawTemplates = this.config.rawTemplates || {}; for (var templateName in rawTemplates) { if (rawTemplates.hasOwnProperty(templateName)) { if (!extraTemplates[templateName]) extraTemplates[templateName] = this.compile(rawTemplates[templateName]); } } } HoganJsUtils.prototype.render = function(namespace, view, params) { var template = this.template(namespace, view); if (template) { return template.render(params); } return null; }; HoganJsUtils.prototype.template = function(namespace, view) { var templateKey = this._templateKey(namespace, view); return this._getTemplate(templateKey); }; HoganJsUtils.prototype._getTemplate = function(templateKey) { var template; if (!this.config.noCache) { template = this._readFromCache(templateKey); } if (!template) { template = this._loadTemplate(templateKey); } return template; }; HoganJsUtils.prototype._loadTemplate = function(templateKey) { var template; try { if (fs.readFileSync) { var templatesPath = path.resolve(__dirname, 'templates'); var templatePath = path.join(templatesPath, templateKey); var templateContent = fs.readFileSync(templatePath + '.mustache', 'utf8'); template = hogan.compile(templateContent); hoganTemplates[templateKey] = template; } } catch (e) { console.error('Failed to read (template: ' + templateKey + ') from fs: ' + e.message); } return template; }; HoganJsUtils.prototype._readFromCache = function(templateKey) { return extraTemplates[templateKey] || hoganTemplates[templateKey]; }; HoganJsUtils.prototype._templateKey = function(namespace, view) { return namespace + '-' + view; }; HoganJsUtils.prototype.compile = function(templateStr) { return hogan.compile(templateStr); }; module.exports.HoganJsUtils = HoganJsUtils; })();