Created
May 28, 2014 12:52
-
-
Save etiennetremel/a845015af9504d7c50d7 to your computer and use it in GitHub Desktop.
Grunt partials injection task
This file contains 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
'use strict'; | |
// Replace html comment tag by content of file, e.g: | |
// e.g: "<!-- partial: partials/header.html -->" will be replaced by the content of "partials/header.html" | |
// Then using grunt in command line: "grunt partials" | |
// Not the best idea ever, but when you have sometimes restriction or to simulate server-side SSI (Server Side Includes), that can be useful. | |
module.exports = function (grunt) { | |
grunt.initConfig({ | |
partials: { | |
options: { | |
files: ['my-directory/index.html'] | |
} | |
} | |
}); | |
// Replace html comments by its partials | |
grunt.registerTask('partials', 'Inject partials to defined files', function() { | |
var options = this.options(); | |
if (!options.files.length) { | |
grunt.log.warn('No files defined.'); | |
return false; | |
} | |
// Tag pattern | |
var pattern = '<!-- partial: ([^ ]+) -->'; | |
// Fetch every tags and associate with its content | |
options.files | |
.forEach(function (filepath) { | |
grunt.log.writeln('Injecting partials into ' + filepath); | |
var file = grunt.file.read(filepath); | |
if (file.length < 1 ) { | |
grunt.log.warn('File was empty?'); | |
} | |
var tags = file.match(new RegExp(pattern, 'gi')); | |
tags.forEach(function (tag) { | |
grunt.log.write('Replacing ' + tag + '...'); | |
var partialPath = (new RegExp(pattern, 'g')).exec(tag); | |
if (partialPath) { | |
var partial = grunt.file.read(partialPath[1]); | |
file = file.replace(partialPath[0], partial); | |
grunt.log.ok(); | |
} else { | |
grunt.log.error(); | |
} | |
}); | |
grunt.file.write(filepath, file); | |
grunt.log.ok('Done ' + filepath); | |
}); | |
}); | |
grunt.registerTask('partials', ['partials']); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment