diff2html/src/hoganjs-utils.js

79 lines
1.8 KiB
JavaScript
Raw Normal View History

2016-04-15 22:08:57 +00:00
/*
*
* Utils (hoganjs-utils.js)
* Author: rtfpessoa
*
*/
(function() {
var fs = require('fs');
var path = require('path');
var hogan = require('hogan.js');
2016-04-25 16:53:54 +00:00
var hoganTemplates = require('./templates/diff2html-templates.js');
2016-04-16 11:06:03 +00:00
2016-04-15 22:08:57 +00:00
var templatesPath = path.resolve(__dirname, 'templates');
var templatesCache = {};
function HoganJsUtils() {
}
2016-04-25 16:53:54 +00:00
HoganJsUtils.prototype.render = function(namespace, view, params, configuration) {
var config = configuration || {};
2016-04-16 10:10:08 +00:00
var templateKey = this._templateKey(namespace, view);
2016-04-25 16:53:54 +00:00
var template = this._getTemplate(templateKey, config);
2016-04-15 22:08:57 +00:00
if (template) {
return template.render(params);
}
return null;
};
2016-04-25 16:53:54 +00:00
HoganJsUtils.prototype._getTemplate = function(templateKey, config) {
var template;
if (!config.noCache) {
template = this._readFromCache(templateKey);
}
2016-04-15 22:08:57 +00:00
2016-04-16 11:06:03 +00:00
if (!template) {
template = this._loadTemplate(templateKey);
}
return template;
};
HoganJsUtils.prototype._loadTemplate = function(templateKey) {
var template;
2016-04-25 16:53:54 +00:00
try {
if (fs.readFileSync) {
var templatePath = path.join(templatesPath, templateKey);
var templateContent = fs.readFileSync(templatePath + '.mustache', 'utf8');
template = hogan.compile(templateContent);
templatesCache[templateKey] = template;
}
} catch (e) {
console.error('Failed to read (template: ' + templateKey + ') from fs: ' + e.message);
2016-04-15 22:08:57 +00:00
}
return template;
};
HoganJsUtils.prototype._readFromCache = function(templateKey) {
2016-04-16 11:06:03 +00:00
return global.browserTemplates && global.browserTemplates[templateKey] ||
hoganTemplates[templateKey] ||
templatesCache[templateKey];
2016-04-15 22:08:57 +00:00
};
HoganJsUtils.prototype._templateKey = function(namespace, view) {
return namespace + '-' + view;
};
module.exports.HoganJsUtils = new HoganJsUtils();
})();