Convert all html templates to single object and store it in a js file

256 views Asked by At

In my project, I am keeping all html files in an organized way such that I can understand. For now, I am keeping them in template folder, something similar to as shown below:

template
    --> Dashboard
       --> left-content.html
       --> right-content.html
    --> Analytics
       --> graph-section.html
    --> profile
       --> basic-profile.html
       --> advanced-profile.html

I want these files to be compressed and get added as key-values of different js file with name templates.js

What I want is something like this:

templates.js

var templates = {
    left-content: "html markup here",
    right-content: "html markup here",
    graph-section: "html markup here",
    basic-profile: "html markup here",
    advanced-profile: "html markup here"
}

So, later using any template plugin like lodash, I can render easily. For example:

var template = _.template(templates['left-content']);
var html = template({data: {/* some data here */}});
document.body.innerHTML = html;

And also, if I add any html files in future, the templates object in templates.js should get updated automatically.

1

There are 1 answers

0
Mr_Green On BEST ANSWER

Here is the code which I am using in my project. I hope this will be helpful.

var gulp = require('gulp');
var fs = require('fs');
var tap = require('gulp-tap');
var path = require('path');
var stringify = require('stringify-object');


// task without watch
gulp.task('template-build', function () {
    var templates = {};

    gulp.src('app/templates/*/*.html')
    // Run a loop through all files in 'app/templates/*/*.html'
    .pipe(tap(function (file, t) {
        // For each file in the loop get "file name" and "file path"
        var filePath = file.relative;
        var fileNameWithExt = path.basename(filePath);
        var fileName = fileNameWithExt.substring(0, fileNameWithExt.lastIndexOf("."));
        templates[fileName] = fs.readFileSync('app/templates/' + filePath, 'utf8');
    }))
        .pipe(tap(function () {
        // Append the above "file name" and "file path"
        fs.writeFile('app/common/templates.js', "var templates =  " + stringify(templates).replace(/[\n\r]*/g, ""));
    }));
});

// this runs the `bundle-templates` task before starting the watch (initial bundle)
gulp.task('watch', ['template-build'], function () {
    // now watch the templates and the js file and rebundle on change
    gulp.watch(['app/templates/*/*.html'], ['template-build']);
});

Later in command prompt: (after visiting my project's directory)

gulp watch

BTW, I am still not be able to compress the html files. If someone has answer please feel free to edit this post.