Skip to content

Commit

Permalink
fix(hugo/hugo-printf.md): printfに追記した
Browse files Browse the repository at this point in the history
  • Loading branch information
shotakaha committed Nov 2, 2024
1 parent 0f0de25 commit 447a39d
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions docs/source/hugo/hugo-printf.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,45 @@
{{ printf "円周率 = %.2f" 3.1416 }}
```

[fmt.Printf](https://gohugo.io/functions/fmt/printf/)関数を使って、文字列を出力できます。
テンプレート内で定義したり、呼び出したりした変数を表示するために使います。
表示する際に[safe.HTML](https://gohugo.io/functions/safe/html/)などの関数にパイプして渡すこともできます。

`printf`関数で文字列を出力できます。
C言語などと同じように、文字列は``%s``、数値は``%d````%f``で指定できます。
その他に真偽値(ブーリアン)は``%t``、とりあえず表示したい場合に``%v``が使えます。
``%+v``にすると、その値のフィールド名(=変数名)も表示して確認できます。

テンプレート内で定義したり、呼び出したりした変数をコンソールに表示して確認できます。
ウェブサイトに表示する文字列の場合は`safe.HTML`などの関数にパイプして適切にエスケープするとよいです。

:::{seealso}

この関数はHugo独自ではなく、Go言語の機能です。
フォーマット文字列の指定子は[fmtのGoドキュメント](https://pkg.go.dev/fmt)を参照してください。

:::

## タイトルを確認したい

```go
{{ printf "サイト名: %s" .Site.Title }}
{{ printf "タイトル: %s" .Title }}
```

## ページ情報を確認したい

```go
{{ printf "%#v" .Page }}
```

`.Page`でそのページオブジェクトに含まれるすべての情報を出力できます。
表示される内容が多いので適宜絞り込む必要があります。
デバッグの初手に使うとよいです。

```go
{{ range $key, $value := .Page }}
<p>{{ $key}}: {{ $value }}</p>
{{ end }}
```

## リファレンス

- [fmt.Printf](https://gohugo.io/functions/fmt/printf/)
- [safe.HTML](https://gohugo.io/functions/safe/html/)

0 comments on commit 447a39d

Please sign in to comment.