これはなに

Hugoで1年以上前の古い記事に警告を表示するようにした。そのときの実装のメモ。
実装

ほぼ以下の記事をパクって参考に実装した。
実装部分だけ抜粋すると以下のとおり。
{{ $lastmod := .Lastmod | default .Date }}
{{ $year := (div (sub now.Unix $lastmod.Unix) 31536000) }}
{{ if ge $year 1 }}
<div class="block-highlight-warning">
<span class="icon-warning">{{ partial "helper/icon" "alert-triangle" }}</span>
<span>この記事は最終更新日から{{ $year }}年以上経過しています。</span>
</div>
{{ end }}
実装にあたり参考元から3点変更した。
まず、元記事では.Lastmod
を直接利用していたが、.Lastmod
がない場合に.Date
を利用するように変更した。
{{ $lastmod := .Lastmod | default .Date }}
次に、1年以上の判定について、元記事ではle
で比較していたが、個人的に比較対象を左に置きたかったのでge
に変更した。
{{ if ge $year 1 }}
最後に、スタイルを好みに変更した。アイコンのあるほうがわかりやすいため、アイコンを追加した。
本サイトでは、Stackテーマを利用しているので、layouts/partials/article/components/content.html
に追加で実装した。そうすると、すべての記事に反映される。
実際の実装
layouts/partials/article/components/content.html
<style>
.block-highlight-warning {
background-color: #ff6f0020;
border-left: 4px solid #ff6f00;
word-break: break-word;
display: flex;
align-items: center;
gap: 1em;
line-height: 1;
padding: 1em;
}
.icon-warning {
display: inline-flex;
align-items: center;
vertical-align: middle;
}
.icon-warning svg {
vertical-align: baseline;
width: 1.5em;
height: 1.5em;
stroke-width: 1.5;
flex-shrink: 0;
}
</style>
{{ $lastmod := .Lastmod | default .Date }}
{{ $year := (div (sub now.Unix $lastmod.Unix) 31536000) }}
<section class="article-content">
{{ if ge $year 1 }}
<div class="block-highlight-warning">
<span class="icon-warning">{{ partial "helper/icon" "alert-triangle" }}</span>
<span>この記事は最終更新日から{{ $year }}年以上経過しています。</span>
</div>
{{ end }}
<!-- Refer to https://discourse.gohugo.io/t/responsive-tables-in-markdown/10639/5 -->
{{ $wrappedTable := printf "<div class=\"table-wrapper\">${1}</div>" }}
{{ .Content | replaceRE "(<table>(?:.|\n)+?</table>)" $wrappedTable | safeHTML }}
</section>
おまけ

ちなみに、N
年以上であることを示さなくていいなら、下記の書き方のほうがシンプルかもしれない。
{{ if ge (now.AddDate -1 0 0) .Date }}
<div class="alert-warning" role="alert">
<strong>Warning!</strong> This article is over a year old.
</div>
{{ end }}