tpl: Add templates.Current

This commit also

* Unexport all internal state in TemplateInfo.
* Make the dispatcher keys used for passing context.Context into uint8 from string to save memory allocations.

Co-authored-by: Joe Mooring <joe@mooring.com>

Updates #13571
This commit is contained in:
Bjørn Erik Pedersen
2025-04-08 18:41:06 +02:00
parent af0602c343
commit d4c6dd16b1
13 changed files with 322 additions and 123 deletions

View File

@@ -14,6 +14,7 @@
package templates_test
import (
"path/filepath"
"testing"
"github.com/gohugoio/hugo/hugolib"
@@ -127,3 +128,41 @@ Try printf: {{ (try (printf "hello %s" "world")).Value }}
"Try printf: hello world",
)
}
func TestTemplatesCurrent(t *testing.T) {
t.Parallel()
files := `
-- hugo.toml --
-- layouts/baseof.html --
baseof: {{ block "main" . }}{{ end }}
-- layouts/all.html --
{{ define "main" }}
all.current: {{ templates.Current.Name }}
all.current.filename: {{ templates.Current.Filename }}
all.base: {{ with templates.Current.Base }}{{ .Name }}{{ end }}|
all.parent: {{ with .Parent }}Name: {{ .Name }}{{ end }}|
{{ partial "p1.html" . }}
{{ end }}
-- layouts/_partials/p1.html --
p1.current: {{ with templates.Current }}Name: {{ .Name }}|{{ with .Parent }}Parent.Name: {{ .Name }}{{ end }}{{ end }}|
p1.current.Ancestors: {{ with templates.Current }}{{ range .Ancestors }}{{ .Name }}|{{ end }}{{ end }}
{{ partial "p2.html" . }}
-- layouts/_partials/p2.html --
p2.current: {{ with templates.Current }}Name: {{ .Name }}|{{ with .Parent }}Parent.Name: {{ .Name }}{{ end }}{{ end }}|
p2.current.Ancestors: {{ with templates.Current }}{{ range .Ancestors }}{{ .Name }}|{{ end }}{{ end }}
p3.current.Ancestors.Reverse: {{ with templates.Current }}{{ range .Ancestors.Reverse }}{{ .Name }}|{{ end }}{{ end }}
`
b := hugolib.Test(t, files)
b.AssertFileContent("public/index.html",
"all.current: all.html",
filepath.FromSlash("all.current.filename: /layouts/all.html"),
"all.base: baseof.html",
"all.parent: |",
"p1.current: Name: _partials/p1.html|Parent.Name: all.html|",
"p1.current.Ancestors: all.html|",
"p2.current.Ancestors: _partials/p1.html|all.html",
)
}