LoginSignup
14
14

More than 3 years have passed since last update.

Hugo の置換で Markdown から生成した HTML を加工する

Last updated at Posted at 2018-12-02

Hugo で Markdown から生成した HTML 要素に class を付与したいことがある。その方法を紹介をする。

置換方法

結論から言うと、

{{ .Content }}

を次のように書き換えれば良い。

{{ .Content | replaceRE "<p>" "<p class=\"myclass\">" | safeHTML }}

上では p タグに myclass というクラスを追加している。追加というよりは hugo の置換機能を使って実現している。

具体的な手順

Hugo に慣れていない人のために具体的な作業内容を紹介する。例として次の Hugo Theme を用いる。

修正すべきファイルを探す

テーマの中のファイルで .Content を含むファイルを探す。

$ grep -r "\.Content" */**/*.html
...
themes/hugo-future-imperfect/layouts/post/content-single.html:    {{ .Content }}
...

いくつかファイルがヒットするが、今回は記事ページに変更を反映させたいのでこのファイルのみを編集する。

ファイルのコピー

ファイルを編集するとは言っても、 Hugo では themes/ 以下の編集は推奨されていない。テーマのアップデートがしにくくなるからである。

今回の場合だと次のようにして

mkdir -p layouts/post
cp themes/hugo-future-imperfect/layouts/post/content-single.html layouts/post/
vim layouts/post/content-single.html

同名ファイル layouts/ 以下にコピーしてそれを編集すれば themes/ のものより優先されて読み込まれるので、テーマのソースを汚すことなくテーマのカスタマイズができる。

次のようなディレクトリ構造になっていれば良い。

layouts/
├── post/
│   └── content-single.html
themes/hugo-future-imperfect/layouts/post/
├── ...
├── content-single.html
├── ...

個人的には theme を fork して submodule として取り込み、ブランチを切ってそこで管理しても良いと思う。テーマへの Pull Request も出しやすくなるし。

書き換え

例えば p タグに myclass を付与したい場合は layouts/post/content-single.html の中の {{ .Content }} を次のように書き換えれば良い。

{{ .Content | replaceRE "<p>" "<p class=\"myclass\">" | safeHTML }}

Markdown から HTML に変換したものを replaceRE で置換して、 \ とかを消すために safeHTML に食わせる、というパイプ処理である。

確認

$ hugo
$ cat ./public/blog/creating-a-new-theme/index.html
...
<p class="myclass">Hugo is Static Site Generator</p>
...

{{ .Content }} で生成される p タグにクラスが付与されていることが確認できる。

ʕ◔ϖ◔ʔ

参考

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14