Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Last active August 29, 2015 14:06
Show Gist options
  • Save kvendrik/8fec8b3a2e6dc801f7d9 to your computer and use it in GitHub Desktop.
Save kvendrik/8fec8b3a2e6dc801f7d9 to your computer and use it in GitHub Desktop.
Grunt include tag parser

A custom grunt task to include files in HTML files.

  • basePath contains the path to your project's root
  • viewsDir contains the path to the folder containing the unparsed HTML files within basePath

The parser will parse the files in viewsDir and write them to your project's root.

Files can be included by creating "include tags".

{{ include "inc/header.html" }}

The script starts searching for the file from the project's root.

grunt.registerTask('parse-includes', 'Parse include tags in HTML files', function(){
//projects root and
//HTML files folder
var basePath = 'public/',
viewsDir = 'views/',
//get all HTML files in folder
htmlFiles = grunt.file.expand(basePath+viewsDir+'*.html'),
currFileContents;
var replaceTags = function(){
//get array of tags used in file
var tags = currFileContents.match(/\{\{\sinclude\s\".+\"\s\}\}/gm);
//if there are tags found
if(tags !== null){
//loop tags
tags.forEach(function(currTag){
//get filepath specified in tag
var filePath = basePath+(currTag.match(/\{\{\sinclude\s\"(.+)\"\s\}\}/)[1]);
//if specified file exists
if( grunt.file.exists(filePath) ){
//replace tag with file contents
currFileContents = currFileContents.replace(currTag, grunt.file.read(filePath));
} else {
grunt.log.warn(filePath + ' does not exist');
}
});
return true;
} else {
return false;
}
};
//loop HTML files
htmlFiles.forEach(function(currFilePath){
//get current file contents
currFileContents = grunt.file.read(currFilePath);
while(replaceTags());
//extract filename from path
var fileName = currFilePath.replace(basePath+viewsDir, '');
//write parsed file to root/filename
grunt.file.write(basePath+fileName, currFileContents);
grunt.log.ok(basePath+fileName+' created from '+currFilePath);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment