- I have HTML template files (underscore template syntax)
- These files are saved in HTML format so they would be easy to edit (IDE syntax highlight)
- I don't want to fetch them with ajax, but rather combine them all and include them as a
js
file. - Using GULP as my task-runner, I would like it to somehow combine all the HTML to something like this, as a javascript file that I could include in my BUILD process:
template_file_name
is the HTML file name.
var templates = {
template_file_name : '...template HTML string...',
template_file_name2 : '...template HTML string...',
template_file_name3 : '...template HTML string...'
}
I don't really know how to approach this, and how to create such text from all the files..yes I can convert each individual file to a string, but how can I put it inside an object?
Update - Oct 25, 15 - ES6 modules:
For those who want your templates as ES6 modules, I have 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";
You can use https://www.npmjs.org/package/gulp-html-to-json.
It has a various feature and very easy to use. It will generate exactly what output you need.
It also has angular
templateCache
generator if you useangularjs
.Another tool I just discovered for all handlebars.js users out there is
gulp-handlebars
.https://www.npmjs.com/package/gulp-handlebars
https://github.com/lazd/gulp-handlebars
After adapting the sample gulp task to my needs I was able to include the
template.js
in myindex.html
and access every single template with a Handlebars wrapper viaTemplate.[filename]()
.e.g.
Template.cart(data);
returns the HTML string with all data filled in.I've found this wonderful tool which does exactly what I want:
https://www.npmjs.org/package/gulp-template-compile
Usage (as simple as):
Then you can access the key/value object with
window.JST
. The values are functions (I don't know why, but it's like that)Update - August 21, 2015
I've decided to use use gulp-file-contents-to-json which is the most simple thing possible for generating JSON from files' contents.
Update - July 19, 2016
I've created 3 NPM packages (might be handy to someone):