tpl/collections: Make dict return nil when no values are provided

This commit is contained in:
Bjørn Erik Pedersen
2026-05-21 10:36:10 +02:00
parent 87f194b249
commit 67aede4364
3 changed files with 37 additions and 0 deletions
+10
View File
@@ -157,7 +157,17 @@ func (ns *Namespace) Delimit(ctx context.Context, l, sep any, last ...any) (stri
// Dictionary creates a new map from the given parameters by
// treating values as key-value pairs. The number of values must be even.
// The keys can be string slices, which will create the needed nested structure.
// If no values are provided, nil will be returned.
func (ns *Namespace) Dictionary(values ...any) (map[string]any, error) {
if len(values) == 0 {
// A common construct is to do
// {{ $opts := dict }}
// And then conditionally assign it if some condition is set.
// The only difference between this and an empty map is that this cannot be written to,
// which is not something we do in Hugo (or: If we do, that's a bug).
// This saves us ~48 bytes in memory allocation on 64-bit architectures.
return nil, nil
}
if len(values)%2 != 0 {
return nil, errors.New("invalid dictionary call")
}
@@ -653,3 +653,21 @@ All.
}
})
}
func TestEmptyDictShouldBeNil(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/home.html --
{{ $d := dict }}
{{ printf "dict: %T %t %d" $d (eq $d nil) (len $d) }}
{{ range $d }}FAIL{{ end }}
index: {{ index $d "foo" }}|
{{ $d2 := dict "foo" "bar" }}
{{ $d3 := merge $d $d2 }}
{{ printf "d3: %v" $d3 }}|
`
hugolib.Test(t, files).AssertFileContent("public/index.html", "dict: map[string]interface {} true 0", "! FAIL", "index: |", "d3: map[foo:bar]|")
}