Gridea的部分主题并不带有自动摘要功能,如果需要摘要得先在文章中手动插入<!--more-->
标记.否则首页就是光溜溜的一片标题,看起来很不舒服.
而且像我这样直接从WordPress迁移很多文章过来的也不可能挨篇文章去加<!--more-->
标记,所以动手修改主题以达到首页自动显示摘要的目的.
本文以Gridea自带主题<Simple1.1.0>为例,讲述如何通过js代码修改添加自定义配置并完成自动摘要功能,修改方法大同小异,其他主题也可以参考.
1.增加自定义配置
编辑文件%Gridea%\themes\simple\config.json
,%Gridea%
就是Gridea设置中的站点源文件路径.
在合适的位置上添加以下代码:
{
"name": "is_auto_excerpt",
"label": "是否启用自动摘要",
"group": "自动摘要",
"value": true,
"type": "switch"
},
{
"name": "auto_excerpt_line",
"label": "自动摘要选取行数",
"group": "自动摘要",
"value": "3",
"type": "input"
},
就完成了主题的页面设置功能,自动摘要选取的行数可以自定义
效果图:

2.首页编写自动摘要功能
编辑文件%Gridea%\themes\simple\templates\index.ejs
在如图所示位置添加代码:

<% if (post.abstract) { %>
<!-- 有手动摘要则加个more链接 -->
<a href="<%= post.link %>">more →</a>
<% } else if (site.customConfig.is_auto_excerpt) { %>
<!-- 没有手动摘要切开启了自动摘要,则根据配置筛除摘要内容 -->
<% var br_position = 0 %>
<% for (var br_count = 0; br_count < site.customConfig.auto_excerpt_line; br_count++) { %>
<% br_position = post.content.indexOf('\n',br_position + 1) %>
<% if(br_position < 0) { break } %>
<% } %>
<% if(br_position > 0) { %>
<p><%- post.content.substring(0, br_position + 1) %>
<% if(post.content.substring(0, br_position + 1).indexOf("<code") > 0) { %>
<!-- 自动摘要出来的内容有<code则补上结尾,防止格式错误 -->
</code></pre>
<% } %>
<p>
<!-- 加个more链接 -->
<a href="<%= post.link %>">more →</a>
<% } %>
<% } %>
3.保存重启Gridea预览查看效果
4.优化
接下来是一个小优化,调整了一下more →
的的样式,看起来更顺眼一些.
编辑文件%Gridea%\themes\simple\assets\styles\main.less
在最后添加:
.post-item .left .post-abstract a {
color: #4c6ef5;
border-bottom: 1px dotted #4c6ef5;
transition: all 0.3s;
}
效果图
