Hugo のカテゴリーを 階層化 する

Uncategorized
361 words

Hugo の カテゴリーは、複数設定しても、同じ階層で表示されます。

これを、

こんな感じにします。

前提条件

Robust」のテーマで説明します。

他のテーマだと、若干修正が必要かもしれません。

準備

階層化するカテゴリーを作ります。

記事の「categories」を複数指定します。

そうすると、階層化して表示するようになります。

1
2
3
categories:
- ゲーム制作
- Cocos Creator

レイアウト修正

「Robust」テーマの「categories.html」を修正します。

1
\themes\hugo_theme_robust\layouts\partials\categories.html

今書かれているコードを消して、下記コードを貼り付けます。

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
33
34
35
36
37
38
{{ $indexScratch := newScratch }}
{{ range $index, $var := $.Site.RegularPages }}
{{ $categories := .Params.categories }}
{{ range $index, $var := $categories }}
{{ if eq $index 0 }}
{{ $indexScratch.SetInMap "articleList" $var "top" }}
{{ else }}
{{ $indexScratch.SetInMap "articleList" $var (index $categories 0) }}
{{ end }}
{{ end }}
{{ end }}
{{ $categories := .Site.Taxonomies.categories }}

<section class="sidebar">
<header>{{ "categories" | upper }}</header>
<ul>
{{ range $key1, $val1 := $indexScratch.Get "articleList" }}
{{ if eq $val1 "top" }}
<li class="side-categories">
<a href="{{ $.Site.BaseURL}}categories/{{ $key1 | urlize }}">{{ $key1 }} <span
class="count">({{ ($categories.Get (replace $key1 " " "-" | lower)).Count }})</span></a>
</li>
<li class="side-categories">
<ul class="children">
{{ range $key2, $val2 := $indexScratch.Get "articleList" }}
{{ if eq $val2 $key1 }}
<li class="side-categories">
<a href="{{ $.Site.BaseURL}}categories/{{ $key2 | urlize }}">{{ $key2 }} <span
class="count">({{ ($categories.Get (replace $key2 " " "-" | lower)).Count }})</span></a>
</li>
{{ end }}
{{ end }}
</ul>
</li>
{{ end }}
{{ end }}
</ul>
</section>

CSS 修正

「Robust」テーマの「custom.css」に スタイルを追加します。

1
\themes\hugo_theme_robust\layouts\partials\custom.css
1
2
3
4
5
6
7
8
9
10
.side-categories {
list-style-type: none;
line-height: 2;
margin: 0;
padding: 0;
}

.children li {
margin-left: 16px;
}

おわりに

ちょっと回りくどいやり方をしてますが、思い通りの表示が出来ました。

WordPress のお手軽さが身にしみます。