Backtestshugorun-20261024-162305#15077
Make .Render take additional data
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches change the Render signature to variadic `any` across the interface, lazy provider, nop page, and test helper, and both thread a custom data context into executeToString. The decisive difference is argument order. The issue explicitly proposes `PAGE.Render [DATA] NAME` with the optional data before the template name, and Patch A implements exactly that (0 args error, 1 arg = name, 2 args = data then name). Patch B instead implements `VIEW [CONTEXT]`, reversing the order, so the call form the issue specifies (`.Render (dict ...) "summary"`) would fail in B with a cast error on the dict. The independent tests passing on both suggests those tests did not pin the order, so they do not rescue B here. Patch A is also more complete: it updates the user-facing docs (Render.md signature, example, and the partial-comparison table that previously said extra context could not be passed), and its tests cover the no-data path, data path, subdir view resolution, nil/empty layout, too-many-args, invalid layout type, and template-not-found with data. Patch B's tests are narrower (one happy path, two error cases) and it ships no documentation. Both handle errors reasonably; A's error messages reference the documented `[DATA] NAME` form while B's reference its own invented `VIEW [CONTEXT]` form. A resolves the issue as specified; B solves a slightly different API.
Four judges ruled on this ticket in parallel, and the verdict comes from counting their votes. Each saw the issue and the two patches, labelled A and B in random order (two of them saw ours as A), with issue links and version numbers removed. Where tests could check the fix, they also saw the results of tests a separate agent wrote for the issue, run on both patches. None was told which patch was ours. The reasoning above is one judge's, shown verbatim.
Solve
1h 52m
Wall-clock time in the container
Full test suite
No new failures
2,273 passed · 6 skipped · 2,322 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
128vs 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
docs/content/en/methods/page/Render.mdindex 044121743..7e2294455 100644@@ -6,7 +6,7 @@ keywords: [] params: functions_and_methods: returnType: template.HTML- signatures: [PAGE.Render NAME]+ signatures: [PAGE.Render [DATA] NAME] aliases: [/functions/render] --- @@ -21,11 +21,21 @@ 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. +To pass additional data to the template, provide it before the template name. If set, `DATA` is passed to the template as its context instead of the page, so include the page in it if you need it:++```go-html-template+{{ range site.RegularPages }}+ {{ .Render (dict "page" . "headingLevel" 3) "summary" }}+{{ end }}+```++Then, in the "summary" template, access the values with `.page` and `.headingLevel`.+ 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 `DATA`, which is then used as the 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..5c318be9b 100644@@ -104,21 +104,42 @@ func (pco *pageContentOutput) Reset() { pco.renderHooks = &renderHooks{} } -func (pco *pageContentOutput) Render(ctx context.Context, layout ...string) (template.HTML, error) {- if len(layout) == 0 {+// Render renders the given layout with this page, or DATA if set, as context.+// It takes the form [DATA] NAME, where DATA, if set, is used as the context passed to the template.+func (pco *pageContentOutput) Render(ctx context.Context, args ...any) (template.HTML, error) {+ // Make sure to send the *pageState and not the *pageContentOutput to the template.+ var data any = pco.po.p+ var layoutv any++ switch len(args) {+ case 0: return "", errors.New("no layout given")+ case 1:+ layoutv = args[0]+ case 2:+ data, layoutv = args[0], args[1]+ default:+ return "", fmt.Errorf("too many arguments to Render, expected [DATA] NAME, got %d arguments", len(args)) }- templ, found, err := pco.po.p.resolveTemplate(layout...)++ layout, err := cast.ToStringE(layoutv)+ if err != nil {+ return "", fmt.Errorf("invalid layout name %v (%T) given to Render: %w", layoutv, layoutv, err)+ }+ if layout == "" {+ return "", errors.New("no layout given")+ }++ 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)+ 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..4b55230ac 100644@@ -2259,6 +2259,75 @@ should-not-match{{- /**/ -}} b.Assert(err, qt.ErrorMatches, `.*template "foo/missing" not found.*`) } +// See issue 15077.+func TestRenderViewWithData(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['home','rss','section','sitemap','taxonomy','term']+-- content/s1/p1.md --+---+title: p1+---+-- layouts/page.html --+nodata: {{ .Render "myview" }}|+withdata: {{ .Render (dict "page" . "foo" "bar") "mydataview" }}|+subdir: {{ .Render (dict "page" . "foo" "baz") "sub/mydataview" }}|+-- layouts/myview.html --+{{ .Title }}{{- /**/ -}}+-- layouts/s1/mydataview.html --+s1: {{ .page.Title }}|{{ .page.RelPermalink }}|{{ .foo }}{{- /**/ -}}+-- layouts/sub/mydataview.html --+sub: {{ .page.Title }}|{{ .foo }}{{- /**/ -}}+`++ b := Test(t, files)+ b.AssertFileContent("public/s1/p1/index.html",+ "nodata: p1|",+ "withdata: s1: p1|/s1/p1/|bar|",+ "subdir: sub: p1|baz|",+ )+}++// See issue 15077.+func TestRenderViewWithDataErrors(t *testing.T) {+ t.Parallel()++ filesTemplate := `+-- hugo.toml --+disableKinds = ['home','rss','section','sitemap','taxonomy','term']+-- content/p1.md --+---+title: p1+---+-- layouts/page.html --+TEMPLATE+-- layouts/myview.html --+myview{{- /**/ -}}+`++ for _, test := range []struct {+ name string+ template string+ expect string+ }{+ {"no args", `{{ .Render }}`, `.*no layout given.*`},+ {"nil layout", `{{ .Render nil }}`, `.*no layout given.*`},+ {"empty layout with data", `{{ .Render (dict "a" 1) "" }}`, `.*no layout given.*`},+ {"too many args", `{{ .Render "a" "b" "myview" }}`, `.*too many arguments to Render.*`},+ {"invalid layout", `{{ .Render "data" (slice 1 2) }}`, `.*invalid layout name.*`},+ {"not found with data", `{{ .Render (dict "a" 1) "missing" }}`, `.*template "missing" not found.*`},+ } {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()+ files := strings.ReplaceAll(filesTemplate, "TEMPLATE", test.template)+ b, err := TestE(t, files)+ b.Assert(err, qt.ErrorMatches, test.expect)+ })+ }+}+ // See issue 15056. func TestRenderViewSubdirTrailingSlash(t *testing.T) { t.Parallel()resources/page/page.goindex 6104eb0ed..4bf2f8fda 100644@@ -328,7 +328,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)+ // It takes an optional data argument before the layout name, e.g.+ // .Render DATA NAME, which, if set, is used as the context passed to the template.+ 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") }
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") }