目次
試しているバージョン
$ hugo version hugo v0.121.1-00b46fed8e47f7bb0a85d7cfc2d9f1356379b740+extended windows/amd64 BuildDate=2023-12-08T08:47:45Z VendorInfo=gohugoio
エラー:inを使った例
{{- $testDict := dict "key1" "value1" "key2" "value2" -}} {{- $testKey := "key1" -}} {{- $result := in $testDict $testKey -}} {{- printf "Test - Result: %v\n" $result -}}
出力結果
Test - Result: false
なぜか、false
となります。確実にキーはあるはずなんですけどね・・・。
解決方法:indexを使いましょう
{{- $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
としています。
出力結果
Test - Result: true