javascriptunderscore.jsgulpunderscore.js-templating

combine html template files into one JS file


  1. I have HTML template files (underscore template syntax)
  2. These files are saved in HTML format so they would be easy to edit (IDE syntax highlight)
  3. I don't want to fetch them with ajax, but rather combine them all and include them as ajs file.
  4. 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";

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

  1. https://www.npmjs.com/package/gulp-file-contents-to-keys
  2. https://www.npmjs.com/package/gulp-file-contents-to-modules
  3. https://www.npmjs.com/package/gulp-template-compile-es6

Solution

  • I've found this wonderful tool which does exactly what I want:

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

    Usage (as simple as):

    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 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):

    1. https://www.npmjs.com/package/gulp-file-contents-to-keys
    2. https://www.npmjs.com/package/gulp-file-contents-to-modules
    3. https://www.npmjs.com/package/gulp-template-compile-es6