tpl/lang: Handle nil values in lang.Merge

This commit is contained in:
Bjørn Erik Pedersen 2022-04-20 17:42:57 +02:00
parent 625be77e08
commit 05b45c35c8
2 changed files with 16 additions and 1 deletions

View file

@ -94,9 +94,9 @@ func TestMergeLanguagesTemplate(t *testing.T) {
b.WithTemplates("home.html", `
{{ $pages := .Site.RegularPages }}
{{ .Scratch.Set "pages" $pages }}
{{ if eq .Language.Lang "nn" }}:
{{ $enSite := index .Sites 0 }}
{{ $frSite := index .Sites 1 }}
{{ if eq .Language.Lang "nn" }}:
{{ $nnBundle := .Site.GetPage "page" "bundle" }}
{{ $enBundle := $enSite.GetPage "page" "bundle" }}
{{ .Scratch.Set "pages" ($pages | lang.Merge $frSite.RegularPages| lang.Merge $enSite.RegularPages) }}
@ -106,6 +106,10 @@ func TestMergeLanguagesTemplate(t *testing.T) {
{{ $pages2 := .Scratch.Get "pages2" }}
Pages1: {{ range $i, $p := $pages }}{{ add $i 1 }}: {{ .File.Path }} {{ .Language.Lang }} | {{ end }}
Pages2: {{ range $i, $p := $pages2 }}{{ add $i 1 }}: {{ .Title }} {{ .Language.Lang }} | {{ end }}
{{ $nil := resources.Get "asdfasdfasdf" }}
Pages3: {{ $frSite.RegularPages | lang.Merge $nil }}
Pages4: {{ $nil | lang.Merge $frSite.RegularPages }}
`,
"shortcodes/shortcode.html", "MyShort",
@ -117,6 +121,10 @@ Pages2: {{ range $i, $p := $pages2 }}{{ add $i 1 }}: {{ .Title }} {{ .Language.L
b.AssertFileContent("public/nn/index.html", "Pages1: 1: p1.md en | 2: p2.nn.md nn | 3: p3.nn.md nn | 4: p4.md en | 5: p5.fr.md fr | 6: p6.nn.md nn | 7: p7.md en | 8: p8.md en | 9: p9.nn.md nn | 10: p10.fr.md fr | 11: p11.md en | 12: p12.nn.md nn | 13: p13.md en | 14: p14.md en | 15: p15.nn.md nn")
b.AssertFileContent("public/nn/index.html", "Pages2: 1: doc100 en | 2: doc101 nn | 3: doc102 nn | 4: doc103 en | 5: doc104 en | 6: doc105 en")
b.AssertFileContent("public/nn/index.html", `
Pages3: Pages(3)
Pages4: Pages(3)
`)
}
func newTestSiteForLanguageMerge(t testing.TB, count int) *sitesBuilder {

View file

@ -24,6 +24,7 @@ import (
translators "github.com/gohugoio/localescompressed"
"github.com/pkg/errors"
"github.com/gohugoio/hugo/common/hreflect"
"github.com/gohugoio/hugo/deps"
"github.com/spf13/cast"
)
@ -250,6 +251,12 @@ type pagesLanguageMerger interface {
// Merge creates a union of pages from two languages.
func (ns *Namespace) Merge(p2, p1 any) (any, error) {
if !hreflect.IsTruthful(p1) {
return p2, nil
}
if !hreflect.IsTruthful(p2) {
return p1, nil
}
merger, ok := p1.(pagesLanguageMerger)
if !ok {
return nil, fmt.Errorf("language merge not supported for %T", p1)