Skip to content

Instantly share code, notes, and snippets.

@nsisodiya
Created April 30, 2014 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nsisodiya/76ba7acab9261e817b36 to your computer and use it in GitHub Desktop.
Save nsisodiya/76ba7acab9261e817b36 to your computer and use it in GitHub Desktop.
Hints for using underscore template
module.exports = function(grunt) {
"use strict";
// Project configuration.
var resourceFiles = grunt.file.readJSON('src/resource/resource.json');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
template: {
files: resourceFiles.templateFiles.map(function(v, i) {
return "./src/" + v;
}),
tasks: ['html2js']
}
}
});
grunt.registerTask('html2js', "Converting HTML templates into JS", function() {
var _ = require('underscore');
//You can Remove templateSettings portion if you want to use default template.
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
_.templateSettings.evaluate = /<!--([\s\S]+?)-->/g;
_.templateSettings.escape = /\{\{-(.+?)\}\}/g;
var src = "";
resourceFiles.templateFiles.map(function(v, i) {
return "./src/" + v;
}).forEach(function(file) {
var filetext = grunt.file.read(file).split("\t").join("")
.split("\n").join("")
.split(">").map(function(v) {
return v.trim();
}).join(">");
src = src + "App.compiledTemplates[\"" + file.split('/').pop() + "\"] = " + _.template(filetext).source + ";\n";
});
grunt.file.write('src/js/services/template.js', "(function(){ App.compiledTemplates = {};" + src + "})();");
console.log("src/js/services/template.js Generated");
});
};
App.templateResolverService = function(id, model) {
if (model === undefined) {
model = {};
}
return App.compiledTemplates[id](model);
}
var DTO = {
userList : ["A","B","C"]
configData : {
..
..
..
}
}
var strHtml = App.templateResolverService("showMore.html", DTO);
this.$el.html(strHTML);
{
"js": {},
"scss": {},
"templateFiles": [
"js/widgets/showMore/showMore.html",
"js/widgets/tooltipToggle/tooltipToggle.html",
"js/modules/genericModalBox/genericModalBox.html",
"js/modules/importItemPopup/importItemPopup.html",
"js/widgets/charts/PieChart/pieChart.html"
]
}
@nsisodiya
Copy link
Author

Because, gist was not allowing me to use "src/js/widgets/showMore/showMore.js" as file name, I have used "src\js\widgets\showMore\showMore.js".
I hope this will be clear.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment