Combine html template files into a single JS file

template_file_name is the name of the HTML file.

 var templates = { template_file_name : '...template HTML string...', template_file_name2 : '...template HTML string...', template_file_name3 : '...template HTML string...' } 

I really don’t know how to approach this, and how to create such text from all files. I can convert every single file to a string, but how can I put it inside an object?


Update - October 25th, 15th - ES6 Modules:

For those who want your templates to be ES6 modules, I created gulp-file-contents-to-modules

Demo output:

 export var file_name = "This is bar."; export var file_name2 = "This is foo.\r\n"; export var my-folder__file_name = "This is baz.\r\n"; 

All my NPM packages related to combining template files with gulp:

+7
javascript gulp underscore.js-templating
source share
3 answers

I found this wonderful tool that does exactly what I want:

https://www.npmjs.org/package/gulp-template-compile

Usage (as simple):

 gulp.task('templates', function () { gulp.src('./views/templates/**/*.html') .pipe(template()) // converts html to JS .pipe(concat('templates.js')) .pipe(gulp.dest('./js/dist/')) }); 

Then you can access the key / value object using window.JST . Values ​​are functions (I don't know why, but it is)

Update - August 21, 2015

I decided to use gulp-file-contents-to-json , which is the easiest thing to generate JSON content from files.

Update July 19, 2016

I created 3 NPM packages (can help someone):

+2
source share

You can use https://www.npmjs.org/package/gulp-html-to-json .

It has a different function and is very easy to use. It will generate exactly what you need.

 var templates = { template_file_name : '...template HTML string...', template_file_name2 : '...template HTML string...', template_file_name3 : '...template HTML string...' } 

It also has an angular templateCache generator if you use angularjs .

0
source share

Another tool I just discovered for all handlebars.js users is gulp-handlebars .

https://www.npmjs.com/package/gulp-handlebars

https://github.com/lazd/gulp-handlebars

After adapting the gulp task to my needs, I was able to include template.js in my index.html and access each individual template using the Handlebars shell via Template.[filename]() .

eg. Template.cart(data); returns an HTML string with all the data filled in.

0
source share

All Articles