Debian Codegraph @

tpl/templates/decorator_falsy_test.go

raw
1 // Copyright 2025 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package templates_test
15
16 import (
17 "testing"
18
19 "github.com/gohugoio/hugo/hugolib"
20 )
21
22 // TestDecoratorPartialFalsyReturn tests that partial decorators work correctly
23 // when a partial returns a falsy value (false, nil, ""). This was a bug in
24 // v0.154.0-v0.154.5 where the decorator stack would become unbalanced.
25 // See https://github.com/gohugoio/hugo/issues/14419
26 func TestDecoratorPartialFalsyReturn(t *testing.T) {
27 t.Parallel()
28
29 files := `
30 -- hugo.toml --
31 disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]
32 -- content/p1.md --
33 ---
34 title: "Page 1"
35 ---
36 -- layouts/_partials/a.html --
37 {{ $result := dict }}
38 {{ with partialCached "b.html" . .RelPermalink }}
39 {{ $result = . }}
40 {{ end }}
41 {{ return $result }}
42 -- layouts/_partials/b.html --
43 {{ $result := dict }}
44 {{ with partialCached "c.html" . "key1" }}
45 {{ $result = merge $result (dict "c" .) }}
46 {{ end }}
47 {{ with partialCached "d.html" . "key2" }}
48 {{ $result = merge $result (dict "d" .) }}
49 {{ end }}
50 {{ return $result }}
51 -- layouts/_partials/c.html --
52 {{ return false }}
53 -- layouts/_partials/d.html --
54 {{ return "truthy" }}
55 -- layouts/home.html --
56 {{ range site.RegularPages }}
57 {{ with partialCached "a.html" (dict "Page" . "RelPermalink" .RelPermalink) .RelPermalink }}d:{{ .d }}{{ end }}
58 {{ end }}$
59 `
60 b := hugolib.Test(t, files)
61
62 b.AssertFileContent("public/index.html", "d:truthy", "$")
63 }
64
65 // Issue 14711
66 // When using {{ with partial "name" . }} inside a <script> tag,
67 // the injected else block's empty string return was being JS-escaped to "".
68 func TestDecoratorPartialFalsyReturnInScript(t *testing.T) {
69 t.Parallel()
70
71 files := `
72 -- hugo.toml --
73 disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]
74 -- content/p1.md --
75 ---
76 title: "Page 1"
77 ---
78 -- layouts/_partials/empty.html --
79 {{ return "" }}
80 -- layouts/home.html --
81 <script>
82 {{- with partial "empty" . }}
83 "this-should-be-skipped": "{{ . }}"
84 {{- end }}
85 </script>
86 `
87 b := hugolib.Test(t, files)
88
89 b.AssertFileContent("public/index.html", "! \"\"")
90 }