Think Twice
IT技術メモ | HUGOのメモ
Created: 2024-04-27 / Updated: 2024-04-27

HUGOのdict型に対してのキーの存在チェックにinは使えない


目次


試しているバージョン

Copy
$ hugo version
hugo v0.121.1-00b46fed8e47f7bb0a85d7cfc2d9f1356379b740+extended windows/amd64 BuildDate=2023-12-08T08:47:45Z VendorInfo=gohugoio

エラー:inを使った例

Copy
{{- $testDict := dict "key1" "value1" "key2" "value2" -}}
{{- $testKey := "key1" -}}
{{- $result := in $testDict $testKey -}}
{{- printf "Test - Result: %v\n" $result -}}
出力結果
Copy
Test - Result: false

なぜか、falseとなります。確実にキーはあるはずなんですけどね・・・。

解決方法:indexを使いましょう

Copy
{{- $testDict := dict "key1" "value1" "key2" "value2" -}}
{{- $testKey := "key1" -}}
{{- $result := not (eq (index $testDict $testKey) nil) -}}
{{- printf "Test - Result: %v\n" $result -}}
indexを使えばキーが一致するものがあればその値が取得でき、一致するキーがなければnilが返却されるので、ここではnilでなければキーが存在しているとみなしてtrueとしています。

出力結果
Copy
Test - Result: true

参考

X

Special thanks