jsdoc/rhino_modules/jsdoc/template.js
Matthew Kastor 818e26c5bc Add escape tag for templates
The new underscore template includes a tag sequence for escaping. I
added an override for that tag that is consistent with our overrides for
evaluation and interpolation.
2012-10-19 20:20:17 -04:00

84 lines
2.1 KiB
JavaScript

/**
@overview
@author Rafał Wrzeszcz <rafal.wrzeszcz@wrzasq.pl>
@license Apache License 2.0 - See file 'LICENSE.md' in this project.
*/
var _ = require('underscore'),
fs = require('fs'),
path = require('path');
// override default settings
var settings = {
evaluate: /<\?js([\s\S]+?)\?>/g,
interpolate: /<\?js=([\s\S]+?)\?>/g,
escape: /<\?js~([\s\S]+?)\?>/g
};
/**
@module jsdoc/template
*/
/**
@class
@classdesc Underscore template helper.
@param {string} path - Templates directory.
*/
exports.Template = function(path) {
this.path = path;
this.layout = null;
};
/** Loads template from given file.
@param {string} file - Template filename.
@return {function} Returns template closure.
*/
exports.Template.prototype.load = function(file) {
var _path = path.join(this.path, file);
return _.template(fs.readFileSync(_path), null, settings);
};
// templates cache
var cache = {};
/**
Renders template using given data.
This is low-level function, for rendering full templates use {@link Template.render()}.
@param {string} file - Template filename.
@param {object} data - Template variables (doesn't have to be object, but passing variables dictionary is best way and most common use).
@return {string} Rendered template.
*/
exports.Template.prototype.partial = function(file, data) {
// load template into cache
if (!(file in cache)) {
cache[file] = this.load(file);
}
// keep template helper context
return cache[file].call(this, data);
};
/**
Renders template with given data.
This method automaticaly applies layout if set.
@param {string} file - Template filename.
@param {object} data - Template variables (doesn't have to be object, but passing variables dictionary is best way and most common use).
@return {string} Rendered template.
*/
exports.Template.prototype.render = function(file, data) {
// main content
var content = this.partial(file, data);
// apply layout
if (this.layout) {
data.content = content;
content = this.partial(this.layout, data);
}
return content;
};