给Hugo添加字数统计和阅读时间功能

经常逛别人的博客时发现"共XXX字,阅读大约需要XXX分钟",发现这个功能比较牛X,然后网上搜索了一下,发现hugo有函数支持这个需求的。

修改页面

博客详情页:layouts/_default/single.html

修改single.html代码

找到标题下面的区块,我的是这样子的

 1<h2 class="subheading">{{ .Params.subtitle  }}</h2>
 2    <span class="meta">
 3            Posted by
 4            {{ if .Params.author  }}
 5                    {{ .Params.author  }}
 6            {{ else  }}
 7                    {{ .Site.Title  }}
 8            {{ end  }}
 9            on
10            {{ .Date.Format "Monday, January 2, 2006"  }}
11            {{ if .Site.Params.page_view_conter  }}
12                    {{ partial "page_view_counter.html" .  }}
13            {{ end  }}
14            <!-- Don't show "Last Modified on" if update happened on the same day. -->
15            {{ if (and (not .Lastmod.IsZero) (not (eq (dateFormat "2006-01-02" .Lastmod) (dateFormat "2006-01-02" .Date))))  }}
16            <br>Last Modified on {{ dateFormat "Monday, January 2, 2006" .Params.LastMod  }}
17            {{ end  }}
18    </span>

接下来在page_view_conter处加上字数统计功能,修改后的结果如下:

 1<h2 class="subheading">{{ .Params.subtitle  }}</h2>
 2    <span class="meta">
 3            Posted by
 4            {{ if .Params.author  }}
 5                    {{ .Params.author  }}
 6            {{ else  }}
 7                    {{ .Site.Title  }}
 8            {{ end  }}
 9            on
10            {{ .Date.Format "Monday, January 2, 2006"  }}
11            {{ if .Site.Params.page_view_conter  }}
12                    <span id="busuanzi_container_page_pv">|<span id="busuanzi_value_page_pv"></span><span>
13                    {{ partial "page_view_counter.html" .  }}
14                    阅读 </span></span>|<span class="post-date">共{{ .WordCount  }}字</span>,阅读约<span class="more-meta"> {{ .ReadingTime  }} 分钟</span>
15            {{ end  }}
16            <!-- Don't show "Last Modified on" if update happened on the same day. -->
17            {{ if (and (not .Lastmod.IsZero) (not (eq (dateFormat "2006-01-02" .Lastmod) (dateFormat "2006-01-02" .Date))))  }}
18            <br>Last Modified on {{ dateFormat "Monday, January 2, 2006" .Params.LastMod  }}
19            {{ end  }}
20    </span>

修改配置文件

修改config.toml配置文件,将page_view_conter的值修改为true

效果如下:

阅读统计,字数统计,阅读时间

参考

Hugo成功添加字数统计和阅读时间