Skip to content

Instantly share code, notes, and snippets.

@rjz
Forked from cookrn/_readme.md
Last active December 19, 2015 10:09
Show Gist options
  • Save rjz/5938713 to your computer and use it in GitHub Desktop.
Save rjz/5938713 to your computer and use it in GitHub Desktop.
Grunt task for client-side EJS
// Concat EJS templates for use in client-side application
// Based on https://gist.github.com/cookrn/3001401
//
// Supports features found in `_.template()` -- EJS extras not included!
//
var path = require('path');
module.exports = function (grunt) {
'use strict';
var ejs = function ejs (files, options) {
var content,
namespace,
templates = {};
namespace = 'window.' + options.namespace;
content = namespace + ' = _.extend({}, ' + namespace + ', ';
files.forEach(function (filepath) {
var key,
obj = templates,
template = grunt.file.read(filepath);
filepath = filepath.replace(options.basePath, '').split(path.sep);
if (filepath[0] == '') filepath = filepath.slice(1);
key = path.basename(filepath.pop(), '.ejs');
filepath.forEach(function (segment) {
obj = obj[segment] = (obj[segment] || {});
});
obj[key] = template
.replace(/(?:\\[ntr])+/g, ' ')
.replace(/[\s\t]+/g, ' ');
});
content += JSON.stringify(templates);
return content + ');';
};
grunt.registerMultiTask('ejs', 'Compile ejs templates to JST file', function () {
var options = this.options({
basePath: '',
namespace: 'JST',
requireJs: false
});
this.files.forEach(function (file) {
// Create JST file.
var content = ejs(file.src, options);
if (options.requireJs) {
content = 'define([], function () {\n' + content + '\n});';
}
grunt.file.write(file.dest, content);
// Fail task if errors were logged.
if (grunt.errors) return false;
// Otherwise, print a success message.
grunt.log.writeln( 'File "' + file.dest + '" created.' );
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment