mew-template
Version:
Precompile template to cmd module
128 lines (110 loc) • 3.48 kB
JavaScript
var dot = require('dot');
var xtemplate = require('xtemplate');
var handlebars = require('handlebars');
var jstOld = require('./lib/jst-old');
var jst = require('./lib/jst');
var defaultSettings = {
evaluate: /\{\{([\s\S]+?)\}\}/g,
interpolate: /\{\{=([\s\S]+?)\}\}/g,
encode: /\{\{!([\s\S]+?)\}\}/g,
use: /\{\{#([\s\S]+?)\}\}/g,
define: /\{\{##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\}\}/g,
conditional: /\{\{\?(\?)?\s*([\s\S]*?)\s*\}\}/g,
iterate: /\{\{~\s*(?:\}\}|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\}\})/g,
varname: 'it',
strip: true,
append: true,
selfcontained: false
};
var braceSettings = {
evaluate: /\<\%([\s\S]+?)\%\>/g,
interpolate: /\<\%=([\s\S]+?)\%\>/g,
encode: /\<\%!([\s\S]+?)\%\>/g,
use: /\<\%#([\s\S]+?)\%\>/g,
define: /\<\%##\s*([\w\.$]+)\s*(\:|=)([\s\S]+?)#\%\>/g,
conditional: /\<\%\?(\?)?\s*([\s\S]*?)\s*\%\>/g,
iterate: /\<\%~\s*(?:\%\>|([\s\S]+?)\s*\:\s*([\w$]+)\s*(?:\:\s*([\w$]+))?\s*\%\>)/g,
varname: 'it',
strip: true,
append: true,
selfcontained: false
};
function mix() {
var args = [].slice.call(arguments);
var ret = args[0];
var rest = args.slice(1);
rest.forEach(function(o) {
for (var k in o) {
if (o.hasOwnProperty(k)) {
ret[k] = o[k];
}
}
});
return ret;
}
function substitute(str, o, regexp) {
var SUBSTITUTE_REG = /\\?\@([^@@]+)\@/g;
return str.replace(regexp || SUBSTITUTE_REG, function(match, name) {
if (match.charAt(0) === '\\') {
return match.slice(1);
}
return (o[name] === undefined) ? '' : o[name];
});
}
module.exports = function(contents, options) {
options = options || {};
// {{}} or <%> only works with dot & jst
var syntax = options.syntax || '{{}}';
// dot jst handlebars xtemplate
var engine = (options.engine || 'dot').toLowerCase();
var compiled;
var templateFn = 'var template = ';
var defines = {
templateFn: '',
renderFn: 'template'
};
var tmpl = [
'define(function () {',
' @templateFn@',
' return {',
' render: function (data) {',
' return @renderFn@(data || {});',
' }',
' };',
'});'
].join('\n');
// reset dot settings
mix(dot.templateSettings, defaultSettings);
if (engine == 'dot' && syntax == '<%%>') {
mix(dot.templateSettings, braceSettings);
}
switch (engine) {
case 'jst':
// compitable with old template
if (syntax == '<%%>') {
templateFn += jstOld.compile(contents);
} else {
templateFn += jst.compile(contents);
}
break;
case 'handlebars':
compiled = handlebars.precompile(contents);
templateFn += 'Handlebars.template(' + compiled + ')';
break;
case 'xtemplate':
compiled = xtemplate.Compiler.compileToStr({
content: contents
});
templateFn += 'new XTemplateRuntime(' + compiled + ')';
break;
case 'dot':
default:
templateFn += dot.compile(contents);
break;
}
if (engine == 'xtemplate') {
defines.renderFn = 'template.render';
}
defines.templateFn = templateFn + ';\n';
return substitute(tmpl, defines);
};