Backtestshugorun-20261002-200313#15077
Make .Render take additional data
Better
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
Both patches fix the core ask the same way. Each changes `Render` to take `args ...any`, uses the optional extra argument as the template's data context in place of the Page, still resolves the template through the page, and updates every interface implementer (LazyContentProvider, nopPage, testPage). Both also report errors for zero arguments, more than two arguments, and a name that is not a string. Patch B goes further in three ways: - **Argument order.** It also accepts the issue's literal `PAGE.Render [DATA] NAME` order. It swaps the arguments only when the first is not a string kind and the second is. Checking the kind rather than the type keeps a `template.HTML` name from being swapped. This adds a small amount of heuristic magic, but the rule is narrow and deterministic. - **Validation.** It rejects an empty layout name. - **Docs.** It updates the documentation page. Patch B's tests are also substantially stronger. They cover: - NAME DATA and DATA NAME orders; - the piped form (`dict ... | .Render "li"`); - a string as data; - no data; - an HTML-typed name; - that template lookup still follows the page's content type (`s1/li.html` for a page in `s1`); - the too-many-arguments error. Patch A's tests cover only the basic dict-context case and two error messages. Its implementation is simpler and arguably cleaner. However, it does not support the issue's suggested DATA-NAME syntax, and its tests are much thinner. On balance, Patch B covers the issue more completely and verifies its behavior more thoroughly, with acceptable added complexity.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
49m 32s
Wall-clock time in the container
Full test suite
No new failures
3,731 passed · 99 skipped · 3,832 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
160vs 90 merged
Changed lines, ours vs merged
The issue
View on GitHubSee https://gohugo.io/methods/page/render/#article
See #15076
PAGE.Render NAME
This has been discussed before.
- The contract has always been that the templates that
.Rendersgets the data context as e.g.page.html, apage.Page. - We can only pass 1 argument to Go's template renderer, which I guess is the blocking reason for not having done this sooner.
So, if we want to do:
PAGE.Render [DATA] NAME
I'm guessing we have 2 top-level options:
- We say that if
DATAis set, we use that as the context passed to the templates,. elsePAGE. - We somehow (e.g. by embeding it in a
{ DataAdditionalContext, Page }struct or putting it into the currentcontext.Context) wrap thePageso you can do both.RelPermalinkand.DataAdditionalContext(naming of the latter is just picked out of a hat without thinking too hard.
The two patches
Our patch+145 −15
docs/content/en/methods/page/Render.mdindex 044121743..db09fcdcb 100644@@ -6,7 +6,7 @@ keywords: [] params: functions_and_methods: returnType: template.HTML- signatures: [PAGE.Render NAME]+ signatures: [PAGE.Render NAME [DATA]] aliases: [/functions/render] --- @@ -21,11 +21,23 @@ Typically used when ranging over a page collection, the `Render` method on a `Pa In the example above, note that the template ("summary") is identified by its file name without directory or extension. +## Passing data++Pass an optional second argument to use as the template context instead of the `Page` object. The template is still resolved using the page's [content type](g), so include the page in the data if the template needs it:++```go-html-template+{{ range site.RegularPages }}+ {{ .Render "summary" (dict "page" . "class" "featured") }}+{{ end }}+```++In the "summary" template, access the page with `.page` and the additional data with `.class`.+ Although similar to the [`partial`][] function, there are key differences. `Render` method|`partial` function :--|:---The `Page` object is automatically passed to the given template. You cannot pass additional context.|You must specify the context, allowing you to pass a combination of objects, slices, maps, and scalars.+The `Page` object is automatically passed to the given template unless you pass a data context.|You must specify the context, allowing you to pass a combination of objects, slices, maps, and scalars. The path to the template is determined by the [content type](g).|You must specify the path to the template, relative to the `layouts/_partials` directory. Consider this layout structure:hugolib/page__per_output.goindex e8dd38ce7..e2ac40ebf 100644@@ -18,6 +18,7 @@ import ( "errors" "fmt" "html/template"+ "reflect" "sync" "sync/atomic" @@ -104,27 +105,66 @@ func (pco *pageContentOutput) Reset() { pco.renderHooks = &renderHooks{} } -func (pco *pageContentOutput) Render(ctx context.Context, layout ...string) (template.HTML, error) {- if len(layout) == 0 {- return "", errors.New("no layout given")+func (pco *pageContentOutput) Render(ctx context.Context, args ...any) (template.HTML, error) {+ layout, data, hasData, err := parseRenderArgs(args)+ if err != nil {+ return "", err }- templ, found, err := pco.po.p.resolveTemplate(layout...)++ templ, found, err := pco.po.p.resolveTemplate(layout) if err != nil { return "", pco.po.p.wrapError(err) } if !found {- return "", fmt.Errorf("template %q not found", layout[0])+ return "", fmt.Errorf("template %q not found", layout) } - // Make sure to send the *pageState and not the *pageContentOutput to the template.- res, err := executeToString(ctx, pco.po.p.s.GetTemplateStore(), templ, pco.po.p)+ if !hasData {+ // Make sure to send the *pageState and not the *pageContentOutput to the template.+ data = pco.po.p+ }++ res, err := executeToString(ctx, pco.po.p.s.GetTemplateStore(), templ, data) if err != nil { return "", pco.po.p.wrapError(fmt.Errorf("failed to execute template %s: %w", templ.Name(), err)) } return template.HTML(res), nil } +// parseRenderArgs parses the arguments to Page.Render, which are the layout name+// and an optional data context, i.e. NAME [DATA].+// For convenience, DATA NAME is also accepted if DATA is not a string.+func parseRenderArgs(args []any) (layout string, data any, hasData bool, err error) {+ switch len(args) {+ case 0:+ return "", nil, false, errors.New("no layout given")+ case 1:+ layout, err = cast.ToStringE(args[0])+ case 2:+ nameArg, dataArg := args[0], args[1]+ isStringKind := func(v any) bool {+ return v != nil && reflect.TypeOf(v).Kind() == reflect.String+ }+ // Use the kind and not the type so e.g. template.HTML names are not swapped.+ if !isStringKind(nameArg) && isStringKind(dataArg) {+ // DATA NAME.+ nameArg, dataArg = dataArg, nameArg+ }+ layout, err = cast.ToStringE(nameArg)+ data, hasData = dataArg, true+ default:+ return "", nil, false, fmt.Errorf("too many arguments: expected a layout name and an optional data context, got %d arguments", len(args))+ }+ if err != nil {+ return "", nil, false, fmt.Errorf("invalid layout name: %w", err)+ }+ if layout == "" {+ return "", nil, false, errors.New("no layout given")+ }+ return layout, data, hasData, nil+}+ func (pco *pageContentOutput) Fragments(ctx context.Context) *tableofcontents.Fragments { return pco.c().Fragments(ctx) }hugolib/page_test.goindex 635358590..91d3ba007 100644@@ -2358,6 +2358,80 @@ layouts/s1/p3/_views/a.html b.AssertFileContent("public/s1/p3/index.html", "p3: layouts/s1/p3/_views/a.html") // fails } +// See issue 15077.+func TestRenderWithData(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['rss','section','sitemap','taxonomy','term']+-- content/p1.md --+---+title: p1+---+-- content/s1/p2.md --+---+title: p2+---+-- layouts/home.html --+{{ range site.RegularPages.ByTitle }}+NameData: {{ .Render "li" (dict "page" . "foo" "bar") }}|+DataName: {{ .Render (dict "page" . "foo" "baz") "li" }}|+Piped: {{ dict "page" . "foo" "piped" | .Render "li" }}|+StringData: {{ .Render "str" "mystring" }}|+NoData: {{ .Render "nodata" }}|+HTMLName: {{ .Render ("str" | safeHTML) "htmlname" }}|+{{ end }}+-- layouts/li.html --+li: {{ .page.Title }}|{{ .foo }}+-- layouts/s1/li.html --+s1/li: {{ .page.Title }}|{{ .foo }}+-- layouts/str.html --+str: {{ . }}+-- layouts/nodata.html --+nodata: {{ .Title }}+-- layouts/page.html --+{{ .Title }}+`++ b := Test(t, files)++ b.AssertFileContent("public/index.html",+ "NameData: li: p1|bar|",+ "DataName: li: p1|baz|",+ "Piped: li: p1|piped|",+ "StringData: str: mystring|",+ "NoData: nodata: p1|",+ "HTMLName: str: htmlname|",+ // The template is resolved using the page's content type, not the data.+ "NameData: s1/li: p2|bar|",+ "DataName: s1/li: p2|baz|",+ "Piped: s1/li: p2|piped|",+ "NoData: nodata: p2|",+ )+}++// See issue 15077.+func TestRenderWithDataTooManyArgs(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['home','rss','section','sitemap','taxonomy','term']+-- content/p1.md --+---+title: p1+---+-- layouts/page.html --+{{ .Render "li" (dict "a" 1) "extra" }}+-- layouts/li.html --+li+`++ _, err := TestE(t, files)+ qt.Assert(t, err, qt.ErrorMatches, `.*too many arguments.*`)+}+ func TestPageConttentWeight(t *testing.T) { files := ` -- hugo.toml --resources/page/page.goindex 6104eb0ed..37b96d8a0 100644@@ -327,8 +327,12 @@ type PageMetaInternalProvider interface { // PageRenderProvider provides a way for a Page to render content. type PageRenderProvider interface {- // Render renders the given layout with this Page as context.- Render(ctx context.Context, layout ...string) (template.HTML, error)+ // Render renders the given layout.+ // The first argument is the layout name, e.g. "summary".+ // An optional second argument is the data passed to the template as context;+ // if not set, this Page is used as context.+ // The template is always resolved using this Page.+ Render(ctx context.Context, args ...any) (template.HTML, error) // RenderString renders the first value in args with the content renderer defined // for this Page. // It takes an optional map as a second argument:resources/page/page_lazy_contentprovider.goindex 84fb24682..2b0516ac5 100644@@ -117,8 +117,8 @@ func (lcp *LazyContentProvider) Len(ctx context.Context) int { return lcp.init.Value(ctx).Len(ctx) } -func (lcp *LazyContentProvider) Render(ctx context.Context, layout ...string) (template.HTML, error) {- return lcp.init.Value(ctx).Render(ctx, layout...)+func (lcp *LazyContentProvider) Render(ctx context.Context, args ...any) (template.HTML, error) {+ return lcp.init.Value(ctx).Render(ctx, args...) } func (lcp *LazyContentProvider) RenderString(ctx context.Context, args ...any) (template.HTML, error) {resources/page/page_nop.goindex 7dbc5f615..1e92f0f82 100644@@ -399,7 +399,7 @@ func (p *nopPage) RelRef(argsm map[string]any) (string, error) { return "", nil } -func (p *nopPage) Render(ctx context.Context, layout ...string) (template.HTML, error) {+func (p *nopPage) Render(ctx context.Context, args ...any) (template.HTML, error) { return "", nil } resources/page/testhelpers_test.goindex fdaee35c1..2222aca7b 100644@@ -483,7 +483,7 @@ func (p *testPage) RelRefFrom(argsm map[string]any, source any) (string, error) return "", nil } -func (p *testPage) Render(ctx context.Context, layout ...string) (template.HTML, error) {+func (p *testPage) Render(ctx context.Context, args ...any) (template.HTML, error) { panic("testpage: not implemented") }
Merged fix · PR #+77 −13
hugolib/page__per_output.goindex e8dd38ce7..05bb49132 100644@@ -104,21 +104,34 @@ func (pco *pageContentOutput) Reset() { pco.renderHooks = &renderHooks{} } -func (pco *pageContentOutput) Render(ctx context.Context, layout ...string) (template.HTML, error) {- if len(layout) == 0 {- return "", errors.New("no layout given")+func (pco *pageContentOutput) Render(ctx context.Context, args ...any) (template.HTML, error) {+ if len(args) == 0 {+ return "", errors.New("no view given") }- templ, found, err := pco.po.p.resolveTemplate(layout...)+ if len(args) > 2 {+ return "", errors.New("too many arguments, expected VIEW [CONTEXT]")+ }+ view, err := cast.ToStringE(args[0])+ if err != nil {+ return "", fmt.Errorf("failed to convert view argument to string: %w", err)+ }++ // Make sure to send the *pageState and not the *pageContentOutput to the template.+ var data any = pco.po.p+ if len(args) == 2 {+ data = args[1]+ }++ templ, found, err := pco.po.p.resolveTemplate(view) if err != nil { return "", pco.po.p.wrapError(err) } if !found {- return "", fmt.Errorf("template %q not found", layout[0])+ return "", fmt.Errorf("template %q not found", view) } - // Make sure to send the *pageState and not the *pageContentOutput to the template.- res, err := executeToString(ctx, pco.po.p.s.GetTemplateStore(), templ, pco.po.p)+ res, err := executeToString(ctx, pco.po.p.s.GetTemplateStore(), templ, data) if err != nil { return "", pco.po.p.wrapError(fmt.Errorf("failed to execute template %s: %w", templ.Name(), err)) }hugolib/page_test.goindex 635358590..57bcfbe94 100644@@ -1913,6 +1913,56 @@ func TestRenderWithoutArgument(t *testing.T) { b.Assert(err, qt.IsNotNil) } +// See issue 15077.+func TestRenderWithContext(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+-- content/p1.md --+---+title: "P1"+---+-- layouts/page.html --+{{ .Render "li" }}|{{ .Render "li" (dict "Title" "Custom") }}+-- layouts/li.html --+Title: {{ .Title }}{{- /**/ -}}+`++ b := Test(t, files)++ b.AssertFileContent("public/p1/index.html", "Title: P1|Title: Custom")+}++// See issue 15077.+func TestRenderWithContextErrors(t *testing.T) {+ t.Parallel()++ filesTemplate := `+-- hugo.toml --+-- content/p1.md --+---+title: "P1"+---+-- layouts/li.html --+li+-- layouts/page.html --+RENDER+`++ for _, test := range []struct {+ render string+ message string+ }{+ {`{{ .Render "li" "foo" "bar" }}`, `(?s).*too many arguments, expected VIEW \[CONTEXT\].*`},+ {`{{ .Render (slice "li") }}`, `(?s).*failed to convert view argument to string: unable to cast \[\]string{"li"} of type \[\]string to string.*`},+ } {+ files := strings.ReplaceAll(filesTemplate, "RENDER", test.render)+ b, err := TestE(t, files)+ b.Assert(err, qt.ErrorMatches, test.message)+ }+}+ // Issue #13021 func TestAllStores(t *testing.T) { t.Parallel()resources/page/page.goindex 6104eb0ed..e0677e1ed 100644@@ -327,8 +327,9 @@ type PageMetaInternalProvider interface { // PageRenderProvider provides a way for a Page to render content. type PageRenderProvider interface {- // Render renders the given layout with this Page as context.- Render(ctx context.Context, layout ...string) (template.HTML, error)+ // Render renders the given view (a layout template) with this Page as+ // the data context, or, if given, the second argument CONTEXT.+ Render(ctx context.Context, args ...any) (template.HTML, error) // RenderString renders the first value in args with the content renderer defined // for this Page. // It takes an optional map as a second argument:resources/page/page_lazy_contentprovider.goindex 84fb24682..2b0516ac5 100644@@ -117,8 +117,8 @@ func (lcp *LazyContentProvider) Len(ctx context.Context) int { return lcp.init.Value(ctx).Len(ctx) } -func (lcp *LazyContentProvider) Render(ctx context.Context, layout ...string) (template.HTML, error) {- return lcp.init.Value(ctx).Render(ctx, layout...)+func (lcp *LazyContentProvider) Render(ctx context.Context, args ...any) (template.HTML, error) {+ return lcp.init.Value(ctx).Render(ctx, args...) } func (lcp *LazyContentProvider) RenderString(ctx context.Context, args ...any) (template.HTML, error) {resources/page/page_nop.goindex 7dbc5f615..1e92f0f82 100644@@ -399,7 +399,7 @@ func (p *nopPage) RelRef(argsm map[string]any) (string, error) { return "", nil } -func (p *nopPage) Render(ctx context.Context, layout ...string) (template.HTML, error) {+func (p *nopPage) Render(ctx context.Context, args ...any) (template.HTML, error) { return "", nil } resources/page/testhelpers_test.goindex fdaee35c1..2222aca7b 100644@@ -483,7 +483,7 @@ func (p *testPage) RelRefFrom(argsm map[string]any, source any) (string, error) return "", nil } -func (p *testPage) Render(ctx context.Context, layout ...string) (template.HTML, error) {+func (p *testPage) Render(ctx context.Context, args ...any) (template.HTML, error) { panic("testpage: not implemented") }