Created
February 10, 2015 12:15
-
-
Save tomaskikutis/517657c4675ce580b1f7 to your computer and use it in GitHub Desktop.
GULP task for compiling HTMLBARS templates for use in the browser
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
var htmlbars = require("gulp-htmlbars"); | |
var tap = require("gulp-tap"); | |
var concat = require("gulp-concat"); | |
var getTemplateNameFromPath = function(path){ | |
// if exist replace \ with / | |
while( path.indexOf("\\") !== -1 ){ | |
path = path.replace("\\", "/"); | |
} | |
var splitPath = path.split("/"); | |
var filenameWithExtension = splitPath[splitPath.length-1]; | |
var folderNameInWhichFileResides = splitPath[splitPath.length-2]; | |
var lastDotIndex = filenameWithExtension.lastIndexOf("."); | |
var filenameWithoutExtension = filenameWithExtension.substring(0, lastDotIndex); | |
var finalTemplateName = filenameWithoutExtension; | |
if( folderNameInWhichFileResides === "components" ){ | |
finalTemplateName = "components/" + finalTemplateName; | |
} | |
return finalTemplateName; | |
}; | |
gulp.task("compileTemplates", function(){ | |
gulp.src("app/templates/**/*.hbs") | |
.pipe(htmlbars({ | |
isHTMLBars: true, | |
templateCompiler: require("./bower_components/ember/ember-template-compiler") | |
})) | |
.pipe(tap(function(file){ | |
var templateName = getTemplateNameFromPath(file.path.toString()); | |
var currentFile = file.contents.toString(); | |
currentFile = currentFile.replace("export default", "Ember.TEMPLATES['" + templateName + "'] = "); | |
file.contents = new Buffer( currentFile ); | |
})) | |
.pipe(concat("compiledTemplates.js")) | |
.pipe(gulp.dest("tmp")); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We're using a nested folder structure for our HBS templates, so I modified the getTemplateNameFromPath to be more flexible:
var getTemplateNameFromPath = function (path) {
// if exist replace \ with /
while (path.indexOf("") !== -1) {
path = path.replace("", "/");
}
var splitPath = path.split("/");
var filenameWithExtension = splitPath[splitPath.length - 1];
var lastDotIndex = filenameWithExtension.lastIndexOf(".");
var filenameWithoutExtension = filenameWithExtension.substring(0, lastDotIndex);
var folderPath = '';
for (var i = splitPath.length - 2; i >= 0; i--) {
if ( splitPath[i] === 'templates' ) { break; }
folderPath = splitPath[i] + '/' + folderPath;
}
var finalTemplateName = folderPath + filenameWithoutExtension;
return finalTemplateName;
};