Javascript 将所有html模板转换为单个对象,并将其存储在js文件中
在我的项目中,我以一种有组织的方式保存所有html文件,以便我能够理解。现在,我将它们保存在Javascript 将所有html模板转换为单个对象,并将其存储在js文件中,javascript,node.js,templates,gulp,Javascript,Node.js,Templates,Gulp,在我的项目中,我以一种有组织的方式保存所有html文件,以便我能够理解。现在,我将它们保存在template文件夹中,类似如下所示: template --> Dashboard --> left-content.html --> right-content.html --> Analytics --> graph-section.html --> profile --> b
template
文件夹中,类似如下所示:
template
--> Dashboard
--> left-content.html
--> right-content.html
--> Analytics
--> graph-section.html
--> profile
--> basic-profile.html
--> advanced-profile.html
我希望这些文件被压缩,并被添加为不同js文件的键值,名为templates.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.js
中的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']);
});
稍后在命令提示符中:(访问我的项目目录后)
顺便说一句,我仍然无法压缩html文件。如果有人有答案,请随时编辑这篇文章
gulp watch