Backtestshugorun-20260930-140149#15077
Make .Render take additional data
Our patch was judged better than the merged fix.
In this judgment, Patch B = our agent, Patch A = the merged fix.
The issue specifies the desired signature as `PAGE.Render [DATA] NAME`: the optional data comes first, and when DATA is set it is used as the template context instead of PAGE. Patch B implements exactly that argument order. With one argument it treats it as the layout name and passes the page as context. With two arguments it takes (data, name). It adds an integration test covering all three cases: no data, a dict containing the page plus extra keys, and a scalar data value. It also updates the docs signature and explanation to match. Patch A implements the reverse order, `Render VIEW [CONTEXT]`, which contradicts the signature the issue asks for. Templates written to the issue's documented form (`.Render (dict ...) "summary"`) would fail under A, because it would try to cast the dict to a view name. A does add error-path tests (too many args, non-string view), which is decent craft. Otherwise the two patches are mechanically equivalent: same interface change, same lazy/nop/test implementations, same cast.ToStringE. B's correctness against the requested API and its broader positive test coverage outweigh A's extra error tests.
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 48s18 turns
Wall-clock time in the container
Full test suite
No new failures
3,730 passed · 99 skipped · 3,831 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
76vs 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..d02349d2b 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,17 @@ 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 a different context to the template, provide it as the first argument. When `DATA` is given, it is passed to the template instead of the `Page` object, so include the page in it if the template needs it:++```go-html-template+{{ .Render (dict "page" . "headingLevel" 3) "summary" }}+```+ 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 passed to the given template, unless you provide `DATA`, which is then passed instead.|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..8a0db27b5 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) {+ var data any = pco.po.p+ var layoutArg any+ switch len(args) {+ case 0: return "", errors.New("no layout given")+ case 1:+ layoutArg = args[0]+ case 2:+ data = args[0]+ layoutArg = args[1]+ default:+ return "", errors.New("too many arguments, expected 1 or 2") }- templ, found, err := pco.po.p.resolveTemplate(layout...)++ layout, err := cast.ToStringE(layoutArg)+ if err != nil {+ return "", err+ }++ 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)+ // Make sure to send the *pageState and not the *pageContentOutput to the template+ // unless data is provided.+ 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..51c8c5894 100644@@ -2089,6 +2089,30 @@ foo b.Assert(err, qt.ErrorMatches, `.*template "view_bar" not found.*`) } +func TestRenderWithData(t *testing.T) {+ t.Parallel()++ files := `+-- hugo.toml --+disableKinds = ['home','rss','section','sitemap','taxonomy','term']+-- content/p1.md --+---+title: p1+---+-- layouts/page.html --+{{ .Render "myview" }}|{{ .Render (dict "page" . "foo" "bar") "myview2" }}|{{ .Render "baz" "myview3" }}+-- layouts/myview.html --+myview: {{ .Title }}{{- /**/ -}}+-- layouts/myview2.html --+myview2: {{ .foo }}|{{ .page.Title }}{{- /**/ -}}+-- layouts/myview3.html --+myview3: {{ . }}{{- /**/ -}}+`++ b := Test(t, files)+ b.AssertFileContent("public/p1/index.html", "myview: p1|myview2: bar|p1|myview3: baz")+}+ // See issue 15057. func TestRenderCaseInsensitiveTemplateName(t *testing.T) { t.Parallel()resources/page/page.goindex 6104eb0ed..386228400 100644@@ -328,7 +328,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)+ // The args are [DATA] NAME: with one argument, NAME is the layout name and+ // this Page is the template context; with two arguments, the first is DATA,+ // which is passed to the template as context instead 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
.Render now accepts an optional data argument: {{ .Render DATA NAME }}. When you pass DATA, the view template gets it as its context instead of the page. {{ .Render NAME }} works exactly as before. ./bt-test couldn't run any tests because its lane has no network and can't download Go modules (errors like lookup proxy.golang.org ... server misbehaving). I ran the same tests with go test, offline, against the module cache at /bt/cache/go-mod, and they pass.
What was wrong: Render(ctx, layout ...string) only took layout names, and it always passed the page as the template context, so there was no way to pass extra data. Go templates only accept one context value, so a second value can't be added alongside the page.
What I changed:
hugolib/page__per_output.go:Rendernow takesargs ...any.- No arguments: the existing "no layout given" error.
- One argument: it is NAME, and the page is the context.
- Two arguments: the first is DATA and becomes the context; the second is NAME.
- More than two: a "too many arguments" error.
- Signature updates: the interface in
resources/page/page.go(with an updated doc comment),page_nop.go,page_lazy_contentprovider.go, and thetestPagehelper inresources/page/testhelpers_test.go. The helper change is only the signature, which it needs to compile. The reviewer found no other code using the old signature. - Docs:
docs/content/en/methods/page/Render.mdnow showsPAGE.Render [DATA] NAMEwith an example. It no longer says you "cannot pass additional context". - Test:
TestRenderWithDatainhugolib/page_test.gocovers the plain.Render "myview", a dict holding the page plus other data, and a plain string as the data.
Test evidence:
- Without the production change,
TestRenderWithDatafails withwrong type for value; expected string; got map[string]interface {}. With it, the test passes. - All
Rendertests in./hugoliband all of./resources/page/...pass, andgo vetis clean. - I dropped a second test for the too-many-arguments error, because the old code already errors on three arguments, so it passed either way.
Requirements:
PAGE.Render [DATA] NAMEsyntax: done, covered byTestRenderWithData.- "If DATA is set, use it as the context, else the page": done, the one-argument call and the dict call in the same test cover both paths.
- Wrapping the page and DATA in one struct or a
context.Context: not done. Only one of the two options was needed, and passing DATA directly is simpler. A wrapper would stop the context from being a realpage.Page, which functions that expect a page would reject. Users who need both can pass(dict "page" . ...), which the test covers. - Keep the existing contract that
.Render NAMEpasses the page: kept. The existingRendertests still pass, includingTestRenderWithoutArgument.
Behaviour to be aware of:
- Two strings mean something new. The old version accepted several layout names but only used the first.
{{ .Render "a" "b" }}now renders layout "b" with the string "a" as context. Nothing in the repo does this, but it may be worth a release note. nilcounts as DATA.{{ .Render nil "x" }}gives the templatenil, not the page.
Everything is left as uncommitted changes. AGENTS.md and CLAUDE.md were already deleted in the working tree before I started, and I didn't touch them.