在我的项目中,我将所有html文件都整理得井井有条,以便我能理解。现在,我将它们保存在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
对象templates.js
应会自动更新。
这是我在项目中使用的代码。我希望这会有所帮助。
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文件。如果有人有答案,请随时编辑此帖子。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句