需求:新增一个模板,用来统计文章篇数和字数,并展示在列表页和归档页

实现步骤:

  1. 新建统计模板
./layouts/partials/stat.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
{{- $scratch := newScratch -}}
{{- $kind := .Kind }}
{{- $pages := where site.RegularPages "Type" "in" site.Params.mainSections -}}

{{- if eq $kind "pages" -}}
{{-   $pages = .pages -}}
{{- else if or (eq $kind `term`) (eq $kind `section`) -}}
{{-   $pages = union .RegularPages .Sections -}}
{{- end -}}

{{- range $pages -}}
{{- $scratch.Add "words" .WordCount -}}
{{- end -}}

{{- $words := $scratch.Get "words" | default 0 }}
{{- printf "%s 篇 %s 字" ((len $pages) | string) ($words | string) -}}
  1. 编辑模板
./layouts/_default/list.html
22
23
24
25
26
27
28
<!-- 列表模板-->

  {{- if (.Param "ShowStatInSectionTermList" | default true) }}
  <sup class="archive-count">&nbsp;&nbsp;{{- partial "stat.html" . }}</sup>
  {{- end }}
<!-- h1 这行上面 -->
</h1>
./layouts/_default/archives.html
20
21
22
23
24
25
26
27
28
29
<!-- 归档模板-->

  <h2 class="archive-year-header">
    {{- replace .Key "0001" "" }}
    {{- if (site.Params.ShowStatInArchive | default true) }}
    <sup class="archive-count">&nbsp;&nbsp;{{- partial "stat.html" (dict "Kind" "pages" "pages" .Pages) }}</sup>
    {{- else }}
    <sup class="archive-count">&nbsp;&nbsp;{{ len .Pages }}</sup>
    {{- end }}
  </h2>
  1. 使用姿势

可直接使用,不需要修改,也可通过以下配置隐藏统计

./config.yml
1
2
3
params:
    ShowStatInSectionTermList: false
    ShowStatInArchive: false