Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
GULP task for compiling HTMLBARS templates for use in the browser
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"));
});
@greghaygood

This comment has been minimized.

Copy link

@greghaygood greghaygood commented Feb 12, 2015

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;
};

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