Backtestshugorun-20261009-153657#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.
The issue explicitly proposes the signature `PAGE.Render [DATA] NAME`, with DATA coming before the template name. Patch B implements this form. It also accepts `NAME DATA`, resolving the ambiguity deterministically: when both arguments are strings, it treats them as DATA NAME, which matches the issue's stated order. Patch A only supports `VIEW [CONTEXT]`, so the issue's proposed call `.Render (dict ...) "summary"` fails with a cast error. A therefore does not deliver the requested API shape. Both patches adopt the issue's first option, using the supplied data as the context instead of the page, and both preserve the default of passing the page when no data is given. Both update the interface, lazy provider, nop page and test helpers consistently. On tests, B's integration test covers data-first, data-last, no data, string data and slice data, and its error cases cover too many arguments, missing layout name, non-string layout and template not found. B also adds focused unit tests for the parsing helper. A tests only the trailing-context form plus two error cases. B also isolates argument parsing in a small documented helper, `ResolveRenderArgs`, and updates the user docs. The one minor caveat is that B's dual-order acceptance adds a little ambiguity, but its string precedence rule is documented and tested. Overall, B matches the issue's requested semantics where A does not, and B is more thoroughly tested.
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
1h 18m
Wall-clock time in the container
Full test suite
No new failures
2,165 passed · 93 skipped · 2,258 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
231vs 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+215 −16
docs/content/en/methods/page/Render.mdindex 044121743..1c7394960 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 the given 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,26 @@ 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. When set, the data is used as the template context instead of the page, so include the page in the data if the template needs it:++```go-html-template+{{ range site.RegularPages }}+ {{ .Render (dict "page" . "showDate" true) "summary" }}+{{ end }}+```++```go-html-template {file="layouts/summary.html"}+<h2><a href="{{ .page.RelPermalink }}">{{ .page.LinkTitle }}</a></h2>+{{ if .showDate }}{{ .page.Date.Format "2006-01-02" }}{{ end }}+```++The data may also be given after the template name, e.g., `{{ .Render "summary" $data }}`, as long as the data is not a string.+ 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 pass your own data as 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..1256d798b 100644@@ -15,7 +15,6 @@ package hugolib import ( "context"- "errors" "fmt" "html/template" "sync"@@ -104,21 +103,26 @@ 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, err := page.ResolveRenderArgs(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)+ }++ if data == nil {+ // Make sure to send the *pageState and not the *pageContentOutput to the template.+ data = pco.po.p } - // 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..23c592232 100644@@ -2458,3 +2458,74 @@ isCJKLanguage: true b.AssertFileContent("public/p500/index.html", "500|500|1") b.AssertFileContent("public/p501/index.html", "501|600|2") }++// See issue 15077.+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 --+DataFirst: {{ .Render (dict "page" . "greeting" "Hello") "view" }}|+DataLast: {{ .Render "view" (dict "page" . "greeting" "Hi") }}|+NoData: {{ .Render "pageview" }}|+StringData: {{ .Render "a string" "strview" }}|+SliceData: {{ .Render (slice 1 2 3) "sliceview" }}|+-- layouts/view.html --+{{- .greeting }} from {{ .page.Title }} at {{ .page.RelPermalink -}}+-- layouts/pageview.html --+{{- .Title -}}+-- layouts/strview.html --+{{- . -}}+-- layouts/sliceview.html --+{{- len . -}}+`++ b := Test(t, files)+ b.AssertFileContent("public/p1/index.html",+ "DataFirst: Hello from p1 at /p1/|",+ "DataLast: Hi from p1 at /p1/|",+ "NoData: p1|",+ "StringData: a string|",+ "SliceData: 3|",+ )+}++func TestRenderWithDataInvalidArgs(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/view.html --+view+`+ for _, test := range []struct {+ name string+ template string+ expect string+ }{+ {"too many", `{{ .Render (dict) "view" "extra" }}`, `.*too many arguments.*`},+ {"no layout", `{{ .Render (dict) (dict) }}`, `.*expected a layout name.*`},+ {"non-string layout", `{{ .Render 32 }}`, `.*expected a layout name.*`},+ {"not found", `{{ .Render (dict) "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)+ })+ }+}resources/page/page.goindex 6104eb0ed..87b4bdbbe 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)+ // It takes an optional data argument, either before or after the layout name.+ // If set, that data is passed to the template as context instead of this Page.+ // See ResolveRenderArgs.+ 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/page_render.gonew file mode 100644index 000000000..a58837694@@ -0,0 +1,52 @@+// Copyright 2025 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package page++import (+ "errors"+ "fmt"+)++// ResolveRenderArgs resolves the arguments passed to Page.Render.+// The supported forms are:+//+// NAME+// DATA NAME+// NAME DATA+//+// The NAME must be a string. When DATA is set (and not nil),+// it is used as the data context passed to the template instead of the Page.+// When DATA is a string, the DATA NAME form is assumed.+func ResolveRenderArgs(args ...any) (layout string, data any, err error) {+ switch len(args) {+ case 0:+ return "", nil, errors.New("no layout given")+ case 1:+ s, ok := args[0].(string)+ if !ok {+ return "", nil, fmt.Errorf("expected a layout name (string), got %T", args[0])+ }+ return s, nil, nil+ case 2:+ if s, ok := args[1].(string); ok {+ return s, args[0], nil+ }+ if s, ok := args[0].(string); ok {+ return s, args[1], nil+ }+ return "", nil, fmt.Errorf("expected a layout name (string) and optional data, got %T and %T", args[0], args[1])+ default:+ return "", nil, fmt.Errorf("too many arguments: expected a layout name (string) and optional data, got %d arguments", len(args))+ }+}resources/page/page_render_test.gonew file mode 100644index 000000000..5ba03faf7@@ -0,0 +1,54 @@+// Copyright 2025 The Hugo Authors. All rights reserved.+//+// Licensed under the Apache License, Version 2.0 (the "License");+// you may not use this file except in compliance with the License.+// You may obtain a copy of the License at+// http://www.apache.org/licenses/LICENSE-2.0+//+// Unless required by applicable law or agreed to in writing, software+// distributed under the License is distributed on an "AS IS" BASIS,+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+// See the License for the specific language governing permissions and+// limitations under the License.++package page++import (+ "testing"++ qt "github.com/frankban/quicktest"+)++func TestResolveRenderArgs(t *testing.T) {+ c := qt.New(t)+ m := map[string]any{"a": 1}++ layout, data, err := ResolveRenderArgs("foo")+ c.Assert(err, qt.IsNil)+ c.Assert(layout, qt.Equals, "foo")+ c.Assert(data, qt.IsNil)++ layout, data, err = ResolveRenderArgs(m, "foo")+ c.Assert(err, qt.IsNil)+ c.Assert(layout, qt.Equals, "foo")+ c.Assert(data, qt.DeepEquals, m)++ layout, data, err = ResolveRenderArgs("foo", m)+ c.Assert(err, qt.IsNil)+ c.Assert(layout, qt.Equals, "foo")+ c.Assert(data, qt.DeepEquals, m)++ layout, data, err = ResolveRenderArgs("data", "foo")+ c.Assert(err, qt.IsNil)+ c.Assert(layout, qt.Equals, "foo")+ c.Assert(data, qt.Equals, "data")++ _, _, err = ResolveRenderArgs()+ c.Assert(err, qt.ErrorMatches, "no layout given")+ _, _, err = ResolveRenderArgs(32)+ c.Assert(err, qt.ErrorMatches, "expected a layout name.*")+ _, _, err = ResolveRenderArgs(m, m)+ c.Assert(err, qt.ErrorMatches, "expected a layout name.*")+ _, _, err = ResolveRenderArgs(m, "foo", "bar")+ c.Assert(err, qt.ErrorMatches, "too many arguments.*")+}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 #15225+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") }