Skip to content

Instantly share code, notes, and snippets.

@hongru
Last active December 18, 2015 06:59
Show Gist options
  • Save hongru/5743338 to your computer and use it in GitHub Desktop.
Save hongru/5743338 to your computer and use it in GitHub Desktop.
ejs2jst
// tasks
// ejs: {
// 'script/view.jst.js': 'view/**/*.ejs'
// },
grunt.registerMultiTask('ejs', 'Compile EJS templates into JST.', function() {
var options = {
client: true,
open: "<%",
close: "%>"
};
grunt.verbose.writeflags(options, 'Options');
var srcFiles;
var taskOutput;
this.files.forEach(function(file) {
srcFiles = grunt.file.expand(file.src);
taskOutput = [];
srcFiles.forEach(function(srcFile) {
taskOutput.push(compileEjs(srcFile, options));
});
if (taskOutput.length > 0) {
grunt.file.write(file.dest, taskOutput.join('\n'));
grunt.log.writeln('File ' + file.dest.cyan + ' created.');
}
});
});
var _uniqueId = function () {
var _id = 0;
return function () {
return _id++;
};
}();
function compileEjs (srcFile, options) {
options = grunt.util._.extend({filename: srcFile}, options);
var srcCode = grunt.file.read(srcFile);
var jstName = srcFile.replace(/\.jst|\.ejs/ig, '');
var _getSuffix = function (jName, fName) {
return "if(typeof module != 'undefined') {"+
" module.exports = "+ fName +";"+
"} else {"+
" window.JST = window.JST || {};"+
" window.JST[\""+jName+"\"] = "+ fName +";"+
"}";
};
try {
var fn = require('ejs').compile(srcCode, options);
// voild 'anonymous' function being rewrote;
var funcName = '__global_JST_FUNC_' + _uniqueId();
return fn.toString().replace(/anonymous/g, funcName)+_getSuffix(jstName, funcName);
} catch (e) {
grunt.log.error(e);
grunt.fail.warn('EJS failed to compile.');
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment