mirror of
https://github.com/gohugoio/hugo.git
synced 2026-08-24 15:28:54 +00:00
tpl/collections: Make dict return nil when no values are provided
This commit is contained in:
@@ -62,6 +62,15 @@ func TestXxHashFromString(t *testing.T) {
|
||||
c.Assert(got, qt.Equals, uint64(7148569436472236994))
|
||||
}
|
||||
|
||||
func TestHashNilMapVsEmptyMap(t *testing.T) {
|
||||
c := qt.New(t)
|
||||
|
||||
var m1 map[string]any = nil
|
||||
m2 := map[string]any{}
|
||||
|
||||
c.Assert(HashString(m1), qt.Equals, HashString(m2))
|
||||
}
|
||||
|
||||
func TestXxHashFromStringHexEncoded(t *testing.T) {
|
||||
c := qt.New(t)
|
||||
s := "The quick brown fox jumps over the lazy dog"
|
||||
|
||||
@@ -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]|")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user