Backtestshugorun-20260922-141813#15077
Make .Render take additional data
The merged fix was judged better than our patch.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches correctly resolve the root cause: they widen Render's signature to `args ...any`, select the page or supplied data as the template context, and execute with it. The single-argument form stays backward compatible in both. The decisive differences are argument order, tests, and craft. Patch A implements `[DATA] NAME` (context first, layout last), which literally echoes the issue's off-hand proposal but conflicts with Hugo's universal templating convention where the template/name comes first and context second (partial NAME CONTEXT). Patch A's rule that 'the last argument is always the layout name' makes the meaning of position 0 shift depending on argument count, which is more surprising and error-prone. Patch B implements `VIEW [CONTEXT]`, keeping the first argument's meaning stable and matching `partial`, the closest analog — the least-surprising extension for a Hugo user. On craft, Patch B uses `cast.ToStringE` for the view name, which is the idiomatic Hugo pattern (cast is used throughout for arg coercion), whereas Patch A uses a strict type assertion. On tests, both add a positive test that fails before and passes after, but Patch B additionally covers two error edges (too many arguments, non-castable view) with regex-matched messages, giving stronger coverage of the boundaries the new signature introduces. Patch A's only clear advantages are faithfulness to the issue's suggested `[DATA] NAME` wording and its inclusion of documentation updates (a genuine plus for a user-facing feature), but the issue text is an open design discussion, not a spec, and the doc benefit does not outweigh the reversed-order usability wart plus weaker error-path tests. Net: Patch B is the better fix on convention-consistency, idiomatic conversion, and test thoroughness.
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
11m 53s31 turns
Wall-clock time in the container
Full test suite
No new failures
3,726 passed · 99 skipped · 3,831 total
Contamination audit
Unknown
See the audit notes for this run
Patch size
82vs 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..b4abb6e2b 100644@@ -1,12 +1,12 @@ --- title: Render-description: Renders the given template with the given page as context.+description: Renders the given template with the given page, or optional additional data, as context. categories: [] 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. +## Pass additional data++You may pass additional data to the template as the first argument. When you do, that data becomes the template context instead of the `Page`:++```go-html-template+{{ .Render (dict "page" . "level" 2) "summary" }}+```++Within the `summary` template, the context (`.`) is the value you passed, so use `.page` to access the page and `.level` to access the other data.+ 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.+By default the `Page` object is passed to the given template. You may optionally pass additional data as the first argument, which then becomes the template context instead of the `Page`.|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..07b8e2aa7 100644@@ -104,21 +104,38 @@ func (pco *pageContentOutput) Reset() { pco.renderHooks = &renderHooks{} } -func (pco *pageContentOutput) Render(ctx context.Context, layout ...string) (template.HTML, error) {- if len(layout) == 0 {+func (pco *pageContentOutput) Render(ctx context.Context, args ...any) (template.HTML, error) {+ if len(args) == 0 { return "", errors.New("no layout given") }- templ, found, err := pco.po.p.resolveTemplate(layout...)+ if len(args) > 2 {+ return "", fmt.Errorf("expected at most 2 arguments to Render ([DATA] NAME), got %d", len(args))+ }++ // The last argument is always the layout name.+ layout, ok := args[len(args)-1].(string)+ if !ok {+ return "", fmt.Errorf("the last argument to Render must be the layout name (a string), got %T", args[len(args)-1])+ }++ // If an additional leading argument is given, use it as the context+ // passed to the template; otherwise render with the Page as context.+ // 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[0]+ }++ 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..41d1edc19 100644@@ -2358,6 +2358,29 @@ layouts/s1/p3/_views/a.html b.AssertFileContent("public/s1/p3/index.html", "p3: layouts/s1/p3/_views/a.html") // fails } +// See issue 15076.+func TestRenderWithAdditionalData(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['home','rss','section','sitemap','taxonomy','term']+-- content/p1.md --+---+title: p1+---+-- layouts/page.html --+{{ .Render (dict "greeting" "hello" "level" 2) "withdata" }}|{{ .Render "nodata" }}+-- layouts/withdata.html --+{{ .greeting }}-{{ .level }}+-- layouts/nodata.html --+{{ .Title }}+`++ b := Test(t, files)+ b.AssertFileContent("public/p1/index.html", "hello-2|p1")+}+ func TestPageConttentWeight(t *testing.T) { files := ` -- hugo.toml --resources/page/page.goindex 6104eb0ed..24de97259 100644@@ -327,8 +327,10 @@ 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 final argument is the layout+ // name; an optional preceding argument is additional data used as the+ // template context in place of 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") }
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") }
What the agent reported
The work is complete. Here is my final report.
What was wrong
Hugo's PAGE.Render NAME template method could only render a view with the Page itself as the template context — there was no way to pass additional data (issue #15076). The blocker was that Go's template renderer takes a single data argument, and the method signature (Render(ctx, layout ...string)) treated every argument as a layout name and always passed the *pageState as context (hugolib/page__per_output.go:107, doc docs/.../Render.md:28 explicitly said "You cannot pass additional context.").
What I changed
Adopted the maintainer's first-listed option (simplest, consistent with partial, no field-shadowing risk): the last argument is the layout NAME; an optional leading argument is DATA that becomes the template context. With no DATA, behavior is byte-identical to before.
hugolib/page__per_output.go— RewroteRendertoRender(ctx, args ...any): last arg → layout name (string), optional first arg → data context (defaults to the*pageState). Added errors for 0 args, >2 args, and a non-string name.resources/page/page.go— Updated thePageRenderProvider.Renderinterface signature + doc comment toargs ...any.resources/page/page_nop.go,resources/page/page_lazy_contentprovider.go— Updated the other two implementers (the lazy one forwardsargs...).resources/page/testhelpers_test.go— Updated thetestPagestub signature (kept body).hugolib/page_test.go— AddedTestRenderWithAdditionalData(issue #15076).docs/content/en/methods/page/Render.md— Updated signature toPAGE.Render [DATA] NAME, the comparison-table row, the front-matter description, and added a "Pass additional data" example section.
Test evidence
- Fail-before verified: with only the production/helper changes reverted (scoped
git stash),TestRenderWithAdditionalDataFAILED — template execution error at.Render (dict …) "withdata"(old...stringsignature rejects a dict). Changes then restored. - Pass-after:
./bt-test ./hugolib/ -run TestRender→ 43/43 PASS, including the new test and all 9 existingTestRenderView*tests plusRenderString/render-hook tests. - Blast radius:
./bt-test ./resources/page/(touched by the interface/nop/lazy/testhelpers changes) → all PASS, 0 fails. - Reviewer confirmed correctness, backward compatibility, consistent implementers, both-path test coverage, and no unrelated/scratch changes.
Requirements checklist
PAGE.Render [DATA] NAME— DATA becomes the context when set, else PAGE (maintainer's option 1) — ✅ Implemented; asserted by the data path (hello-2) and no-data path (.Title→p1) inTestRenderWithAdditionalData.- Maintainer's option 2 (wrap Page in a
{Data, Page}struct / context.Context) — ⏭️ Skipped as the chosen alternative. Option 1 was selected: it's the maintainer's first-listed option, mirrors howpartialtakes an explicit context, keeps the single-argument constraint of Go's renderer, and avoids the field-shadowing hazard of embeddingpage.Page(which already exposes a.Datamethod). Evidence: only one of the two mutually-exclusive options was requested to be picked; the diff implements option 1 end-to-end with passing tests. - Backward compatibility of existing
Render NAME— ✅ Unchanged; all pre-existingTestRenderView*tests still pass and the no-data path passes the*pageStateas before. - Documentation updated — ✅
docs/.../Render.mdsignature, table, description, and new example.
No commits were made; all changes are uncommitted in the working tree. (The AGENTS.md/CLAUDE.md deletions were pre-existing before this session and are unrelated.)