diff options
Diffstat (limited to 'lib/template.js')
-rw-r--r-- | lib/template.js | 30 |
1 files changed, 27 insertions, 3 deletions
diff --git a/lib/template.js b/lib/template.js index 9f32515..dac1201 100644 --- a/lib/template.js +++ b/lib/template.js @@ -1,6 +1,8 @@ var _ = require('lodash'); var Q = require('q'); +var path = require('path'); var nunjucks = require('nunjucks'); +var parsers = require('gitbook-parsers'); var escapeStringRegexp = require('escape-string-regexp'); var batch = require('./utils/batch'); @@ -16,12 +18,25 @@ function normBlockResult(blk) { var TemplateEngine = function(book) { + var that = this; + this.book = book; this.log = this.book.log; + // Template loader + this.loader = new BookLoader(book, { + // Replace shortcuts in imported files + interpolate: function(filepath, source) { + var parser = parsers.get(path.extname(filepath)); + var type = parser? parser.name : null; + + return that.applyShortcuts(type, source); + } + }); + // Nunjucks env this.env = new nunjucks.Environment( - new BookLoader(book), + this.loader, { // Escaping is done after by the markdown parser autoescape: false, @@ -67,7 +82,7 @@ TemplateEngine.prototype.processBlock = function(blk) { // Add to global map if (toAdd) this.blockBodies[blk.id] = blk; - //Parsable block, just return it + // Parsable block, just return it if (blk.parse) { return blk.body; } @@ -349,6 +364,11 @@ TemplateEngine.prototype._applyShortcut = function(parser, content, shortcut) { }); }; +// Apply all shortcuts to some template string +TemplateEngine.prototype.applyShortcuts = function(type, content) { + return _.reduce(this.shortcuts, _.partial(this._applyShortcut.bind(this), type), content); +}; + // Render a string from the book TemplateEngine.prototype.renderString = function(content, context, options) { context = _.extend({}, context, { @@ -369,9 +389,13 @@ TemplateEngine.prototype.renderString = function(content, context, options) { type: null }); if (options.path) options.path = this.book.resolve(options.path); + if (!options.type && options.path) { + var parser = parsers.get(path.extname(options.path)); + options.type = parser? parser.name : null; + } // Replace shortcuts - content = _.reduce(this.shortcuts, _.partial(this._applyShortcut.bind(this), options.type), content); + content = this.applyShortcuts(options.type, content); return Q.nfcall(this.env.renderString.bind(this.env), content, context, options) .fail(function(err) { |