如何在Hexo中折叠代码

​ 添加代码折叠功能,本文基于Cactus主题修改。

  


  

添加折叠js

在 themes/cactus/source/js/main.js 中添加代码:

1
2
3
4
5
6
7
8
$(document).ready(function(){
$(document).on('click', '.fold_hider', function(){
$('>.fold', this.parentNode).slideToggle();
$('>:first', this).toggleClass('open');
});
//默认情况下折叠
$("div.fold").css("display","none");
});

自定义内建标签

在 themes/cactus/scripts 下添加文件tags.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
/*
@haohuawu
修复 Nunjucks 的 tag 里写 ```代码块```,最终都会渲染成 undefined 的问题
https://github.com/hexojs/hexo/issues/2400
*/
const rEscapeContent = /<escape(?:[^>]*)>([\s\S]*?)<\/escape>/g;
const placeholder = '\uFFFD';
const rPlaceholder = /(?:<|&lt;)\!--\uFFFD(\d+)--(?:>|&gt;)/g;
const cache = [];
function escapeContent(str) {
return '<!--' + placeholder + (cache.push(str) - 1) + '-->';
}
hexo.extend.filter.register('before_post_render', function(data) {
data.content = data.content.replace(rEscapeContent, function(match, content) {
return escapeContent(content);
});
return data;
});
hexo.extend.filter.register('after_post_render', function(data) {
data.content = data.content.replace(rPlaceholder, function() {
return cache[arguments[1]];
});
return data;
});

在 themes/cactus/scripts 下添加文件fold.js,代码:

1
2
3
4
5
6
7
8
/* global hexo */
// Usage: {% fold ???? %} Something {% endfold %}
function fold (args, content) {
var text = args[0];
if(!text) text = "点击显/隐";
return '<div><div class="fold_hider"><div class="close hider_title">' + text + '</div></div><div class="fold">\n' + hexo.render.renderSync({text: content, engine: 'markdown'}) + '\n</div></div>';
}
hexo.extend.tag.register('fold', fold, {ends: true});

修改样式

在 themes/cactus/source/css/style.styl 中添加代码:

1
2
3
4
5
6
7
8
9
10
11
.hider_title{
font-family: "Microsoft Yahei";
cursor: pointer;
color: #708090;
}
.close:after{
content: "▼";
}
.open:after{
content: "▲";
}

部署使用

1
2
3
hexo clean
hexo g
hexo d

Demo

「查看代码」
1
2
3
{% fold 「查看代码」 %}
/* source */
{% endfold %}

参考

https://blog.rmiao.top/hexo-fold-block/