Created
February 22, 2013 01:27
-
-
Save karlgoldstein/5010047 to your computer and use it in GitHub Desktop.
Grunt task (v. 0.4.0) for compiling AngularJS templates to JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} | |
}); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you Karl! I used this in recent project and may have to make it a staple in my workflow 👍