Skip to content

Instantly share code, notes, and snippets.

@karlgoldstein
Created February 22, 2013 01:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save karlgoldstein/5010047 to your computer and use it in GitHub Desktop.
Save karlgoldstein/5010047 to your computer and use it in GitHub Desktop.
Grunt task (v. 0.4.0) for compiling AngularJS templates to JavaScript.
/**
* Generates JavaScript version of HTML templates for AngularJS as part of a Grunt build
*
* Allows for bundling into multiple collections, for applications that are distributed across more than one page.
*
* Usage (in grunt.initConfig):
*
* html2js: {
* firstTemplateCollection: {
* src: ['<%= src.first %>'],
* dest: '<%= tmpdir %>/first'
* },
* secondTemplateCollection: {
* src: ['<%= src.second %>'],
* dest: '<%= tmpdir %>/second'
* }
* }
*
* Be sure to add the 'templates' module as a dependency to your main Angular module
*/
module.exports = function (grunt) {
// HTML-2-JS Templates
var path = require('path');
var escapeContent = function(content) {
return content.replace(/"/g, '\\"').replace(/\r?\n/g, '" +\n "');
};
var normalizePath = function(p) {
if ( path.sep !== '/' ) {
p = p.replace(/\\/g, '/');
}
return p;
};
grunt.registerMultiTask('html2js', 'Generate JavaScript version of HTML templates', function() {
var options = this.options({
base: 'src'
});
this.files.forEach(function(f) {
var templates = [];
f.src.forEach(function(src) {
var id = normalizePath(path.relative(options.base, src));
var dest = path.resolve(f.dest, id + '.js');
grunt.log.writeln('Processing ' + src + ' -> ' + dest);
templates.push("'/" + id + "'");
var content = escapeContent(grunt.file.read(src));
var template = 'angular.module("/' + id + '", []).run(["$templateCache", function($templateCache) ' +
'{\n $templateCache.put("/' + id + '",\n "' + content + '");\n}]);\n';
grunt.file.write(dest, template);
});
if (templates.length) {
var template = "angular.module('templates', [" + templates.join(', ') + "]);";
grunt.file.write(path.resolve(f.dest, 'templates.js'), template);
}
});
});
};
@christianbryant-rva
Copy link

Thank you Karl! I used this in recent project and may have to make it a staple in my workflow 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment