diff --git a/src/helpers/underscore-helpers.js b/src/helpers/underscore-helpers.js new file mode 100644 index 0000000..8567e80 --- /dev/null +++ b/src/helpers/underscore-helpers.js @@ -0,0 +1,34 @@ +/** +Template helper definitions for Underscore. +@license MIT. Copyright (c) 2016 hacksalot (https://github.com/hacksalot) +@module handlebars-helpers.js +*/ + + +(function() { + + var HANDLEBARS = require('handlebars') + , _ = require('underscore') + , helpers = require('./generic-helpers'); + + /** + Register useful Underscore helpers. + @method registerHelpers + */ + module.exports = function( theme, opts, cssInfo, ctx, eng ) { + + helpers.theme = theme; + helpers.opts = opts; + helpers.cssInfo = cssInfo; + helpers.engine = eng; + ctx.h = helpers; + + _.each( helpers, function( hVal, hKey ) { + if( _.isFunction( hVal )) { + _.bind( hVal, ctx ); + } + }, this); + + }; + +}()); diff --git a/src/renderers/underscore-generator.js b/src/renderers/underscore-generator.js index 7b7de12..86eaaf9 100644 --- a/src/renderers/underscore-generator.js +++ b/src/renderers/underscore-generator.js @@ -8,7 +8,9 @@ Definition of the UnderscoreGenerator class. - var _ = require('underscore'); + var _ = require('underscore') + , registerHelpers = require('../helpers/underscore-helpers') + , HMSTATUS = require('../core/status-codes'); /** @@ -17,6 +19,23 @@ Definition of the UnderscoreGenerator class. */ var UnderscoreGenerator = module.exports = { + generateSimple: function( data, tpl ) { + + try { + // Compile and run the Handlebars template. + var template = _.template( tpl ); + return template( data ); + } + catch( ex ) { + throw { + fluenterror: template ? + HMSTATUS.invokeTemplate : HMSTATUS.compileTemplate, + inner: ex + }; + } + + }, + generate: function( json, jst, format, cssInfo, opts, theme ) { // Tweak underscore's default template delimeters @@ -31,23 +50,20 @@ Definition of the UnderscoreGenerator class. // Strip {# comments #} jst = jst.replace( delims.comment, ''); - var helpers = require('../helpers/generic-helpers'); - helpers.opts = opts; - helpers.cssInfo = cssInfo; - - // Compile and run the template. TODO: avoid unnecessary recompiles. - var compiled = _.template(jst); - var ret = compiled({ + var ctx = { r: format === 'html' || format === 'pdf' || format === 'png' ? json.markdownify() : json, filt: opts.filters, XML: require('xml-escape'), RAW: json, cssInfo: cssInfo, + //engine: this, headFragment: opts.headFragment || '', - opts: opts, - h: helpers - }); - return ret; + opts: opts + }; + + registerHelpers( theme, opts, cssInfo, ctx, this ); + + return this.generateSimple( ctx, jst ); } };