将所有html模板转换为单个对象,并将其存储在一个js文件中

在我的项目中,我保持所有的html文件有组织的方式,使我能理解。 现在,我将它们保存在template文件夹中,类似于以下所示:

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

我希望这些文件被压缩,并添加为名称templates.js的不同js文件的键值

我想要的是这样的:

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" } 

所以,以后使用任何模板插件如lodash ,我可以很容易地渲染。 例如:

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

而且,如果将来添加任何html文件, templates中的templates对象应该会自动更新。

这是我在我的项目中使用的代码。 我希望这会有所帮助。

 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']); }); 

稍后在命令提示符下:( 在访问我的项目目录之后

 gulp watch 

顺便说一句,我仍然无法压缩的HTML文件。 如果有人有答案,请随时编辑这个职位。