grunt-contrib-jst/tasks/jst.js

70 lines
1.9 KiB
JavaScript
Raw Normal View History

2012-09-11 02:12:23 +08:00
/*
* grunt-contrib-jst
* http://gruntjs.com/
*
* Copyright (c) 2012 Tim Branyen, contributors
* Licensed under the MIT license.
*/
2012-10-19 07:02:45 +08:00
'use strict';
2012-09-11 02:12:23 +08:00
module.exports = function(grunt) {
2012-10-19 07:02:45 +08:00
var _ = require('underscore');
2012-09-12 23:34:53 +08:00
// filename conversion for templates
var defaultProcessName = function(name) { return name; };
2012-09-11 02:12:23 +08:00
2012-10-19 07:02:45 +08:00
grunt.registerMultiTask('jst', 'Compile underscore templates to JST file', function() {
2012-09-11 06:32:35 +08:00
2012-10-19 07:02:45 +08:00
var helpers = require('grunt-lib-contrib').init(grunt);
var options = this.options({
namespace: 'JST',
templateSettings: {}
});
2012-09-11 02:12:23 +08:00
// assign filename transformation functions
var processName = options.processName || defaultProcessName;
2012-10-19 07:02:45 +08:00
grunt.verbose.writeflags(options, 'Options');
2012-09-11 02:12:23 +08:00
2012-11-20 05:24:39 +08:00
var compiled, src, filename;
var nsInfo = helpers.getNamespaceDeclaration(options.namespace);
2012-09-11 02:12:23 +08:00
var files = this.file.src;
2012-11-14 06:12:23 +08:00
var output = files.map(function(file) {
var src = grunt.file.read(file);
try {
compiled = _.template(src, false, options.templateSettings).source;
} catch (e) {
grunt.log.error(e);
grunt.fail.warn('JST failed to compile.');
2012-09-11 02:12:23 +08:00
}
2012-11-14 06:12:23 +08:00
if (options.prettify) {
compiled = compiled.replace(/\n+/g, '');
}
2012-11-14 06:12:23 +08:00
filename = processName(file);
return nsInfo.namespace+'['+JSON.stringify(filename)+'] = '+compiled+';';
2012-09-11 02:12:23 +08:00
});
2012-11-14 06:12:23 +08:00
if(output.length > 0) {
output.unshift(nsInfo.declaration);
if (options.amdWrapper) {
if (options.prettify) {
output.forEach(function(line, index) {
output[index] = " " + line;
});
}
output.unshift("define(function(){");
output.push(" return " + nsInfo.namespace + ";\n});");
}
2012-11-14 06:12:23 +08:00
grunt.file.write(this.file.dest, output.join('\n\n'));
grunt.log.writeln('File "' + this.file.dest + '" created.');
}
2012-09-11 02:12:23 +08:00
});
};