博客标签优化
标签:blog,javascript
之前写过一篇博客开始支持标签,里面说过,生成标签列表的做法是
- 将标签列表的html写入
template.html
- 使用gulp-template-html,将markdown填充到
template.html
模板页,生成文章页面
function* gen_tags_html(tag_list){
var template_path=root_path+'/src/template.html',
content=yield readFileThunk(template_path),
html='<ul>\n';
for(var i=0;i<tag_list.length;i++){
html+="<li><a href='../tag/"+tag_list[i]+"'/>"+tag_list[i]+"</a></li>\n"
}
html+='</ul>\n'
content=content.toString().replace('{{tag_list}}',html)
yield writeFileThunk(template_path,content)
}
但是这样做,在开发环境下有个缺点:停止gulp后,template.html
被修改了,里面有标签列表,需要
git checkout src/template.html
恢复,这对于有代码洁癖的我是不能容忍的!
不将标签列表写入template.html
的话,只能将标签列表传出,供gulp-template-html使用
可以在end事件回调
传出标签列表
var exports = {'instance':tags,'data':{}}
function tags() {
function process (file, enc, cb) {
if (file.isBuffer()) {
...
file.contents = Buffer.from(file.contents, enc);
}
cb(null, file);
}
return through.obj(process).on('end',function(){
co(function* () {
yield [
gen_tags_json(all_tags),
gen_title_path_json(title_path),
]
return yield gen_tags_html(Object.keys(all_tags))
}).then(function(val){
exports.data=val
})
})
}
module.exports = exports
co
里面返回标签列表的html- then回调中,将标签列表的html赋值给exports.data,exports.data是Object,可变对象
- gulp运行时
var tap = require('gulp-tap'),
tags=require('../tags.js');
gulp.task('tags',function(){
return gulp.src([root_path+'/src/markdown/!(index)*'])
.pipe(tags.instance())
.pipe(gulp.dest(root_path+'/src/markdown'))
});
gulp.task('markdown',['tags'], function(){
return gulp.src(root_path+'/src/markdown/*')
.pipe(cache('markdown'))
.pipe(tap(function(file){
file.contents =Buffer.from('<!-- build:tag_list -->'+tags.data+'<!-- /build:tag_list -->'+file.contents.toString())
}))
.pipe(markdown())
.pipe(template(root_path+'/src/template.html'))
....
});
- 执行
tags task
,收集tag,title,path,生成相关json文件及标签列表的html.标签列表的html传给前面的exports.data,因为exports.data是可变对象,此时tags.data保存着标签列表的html - 执行
markdown task
,使用gulp-tap将标签列表拼接成gulp-template-html格式
<!-- build:tag_list -->+tags.data+<!-- /build:tag_list -->
添加到每个markdown文件
- 模板改为
<main>
<article><!-- build:content --></article>
- <nav>{{tag_list}}</nav>
+ <nav><!-- build:tag_list --></nav>
</main>
不定期更新