hexo自定义渲染markdown

以lazyload插件为例,需要替换src标签为data-original,如果还想使用默认的markdown格式,势必要对img的渲染过程进行重载。
首先修改默认的markdown插件,node_modules/hexo-renderer-marked/lib/renderer.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
module.exports = function(data, options) {
// return marked(data.text, assign({
// renderer: new Renderer()
// }, this.config.marked, options));

var curRender = new Renderer(),
markedRenderer = this.markedRenderer;

// init function
if (markedRenderer && typeof(markedRenderer.init) == 'function') {
markedRenderer.init.call(this, data, options);
}

// override marked.Render
if (markedRenderer) {
curRender = assign(curRender, markedRenderer);
}

// get html content
var html = marked(data.text, assign({
renderer: curRender
}, this.config.marked, options));

// complete function
if (markedRenderer && typeof(markedRenderer.complete) == 'function') {
var tmpHtml = markedRenderer.complete.call(this, html);
if (!tmpHtml) {
html = tmpHtml;
}
}
return html;
};

主题目录下新建scripts/marked-renderer.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
hexo.markedRenderer = {
init: function() {
// console.log("hexo.markedRenderer init!");
// Called before rendering
},
complete: function(html) {
// console.log("hexo.markedRenderer complete!");
// Called after rendered

// Deal with html here ...

return html;
},
image: function(href, title, alt) {
// Default method can be accessed via:
// this._super.heading(text, level)
var orimg = '<img data-original="' + href;
if (title) orimg += '" title="' + title;
if (alt) orimg += '" alt="' + alt;
return orimg + '">';
}
};

完成。
参考:
helinjiang/hexo-renderer-marked-enhanced
Support image resizing
jieyou/lazyload