Skip to content

Instantly share code, notes, and snippets.

@tomaskikutis
Created February 10, 2015 12:15
Show Gist options
  • Save tomaskikutis/517657c4675ce580b1f7 to your computer and use it in GitHub Desktop.
Save tomaskikutis/517657c4675ce580b1f7 to your computer and use it in GitHub Desktop.
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
Copy link

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