• SIS Lab
  • >
  • note
  • >
  • 【Hugo】Partial Templateでは複数returnを記述する早期Returnを使えない

【Hugo】Partial Templateでは複数returnを記述する早期Returnを使えない

更新日:2025.04.19 作成日:2025.04.19

Partial Templateを関数代わりに使おうとしたときに、returnを複数記述するとエラーになった。

{{ if isset .Params "img" }}
	{{ return .Params.img }}
{{ else }}
	{{ return "images/nopicture.png" | absURL }}
{{ end }}

ドキュメント Partial templates を確認すると、確かに1つのpartialファイルに1つのreturnだけが許されていると明記されていた。

Only one return statement is allowed per partial file.

早期リターンはせずに、最後に返すようにする。

{{ $image := "" }}

{{ if isset .Params "img" }}
  {{ if strings.HasPrefix .Params.img "http" }}
    {{ $image = .Params.img }}
  {{ else }}
    {{ $image = (print .Params.img | absURL) }}
  {{ end }}
{{ else if eq .Section "blog" }}
  {{ $image = partial "functions/getOgpImageBlog.html" . }}
{{ else if eq .Section "poetry" -}}
  {{ $image = partial "functions/getOgpImagePoetry.html" . }}
{{ else }}
  {{ $image = "images/nopicture.png" | absURL }}
{{ end }}

{{ return $image }}

Related contents