Backtestshugorun-20261024-162305#15373

Issue #15373 Merged fix PR #15376 Run 24 Oct 2026 · run-20261024-162305 gohugoio/hugo

Support relative path calls in partials

Better

Our patch was judged better than the merged fix.

In this judgment, Patch B = our agent, Patch A = the merged fix.

Both patches implement the same core design: intercept names beginning with "./" or "../" in Include/IncludeCached, resolve them against the calling partial's directory taken from the current-template context, reject use outside partials and escapes above the partials root, and track a decoratorOwner so relative calls inside a `with partial` block resolve against the enclosing partial. Both pass eight of nine independent tests. The difference is the templates.Defer case. Patch A tries to support it by copying category and decoratorOwner into the deferred TemplInfo in addDeferredTemplate, but deferred templates are shared between owners with identical bodies, so the stored PathInfo belongs to whichever owner registered first. Two partials in different directories with textually identical defer blocks calling "./util.html" therefore both resolve to the first owner's sibling. The independent test TestBtJudgeRelativeInsideDeferIdenticalBodies confirms this: FAIL-ASSERT on A, PASS on B. Patch A's own defer test only has a single owner, so it does not catch the bug. Patch B instead resolves deferred templates via cur.Parent, the template that actually called templates.Defer, with an explicit comment about body sharing and a test with two identical defer blocks in different directories. This is a genuine correctness gap in A on a scenario the issue's "full path independent" goal implies, and A's change to addDeferredTemplate (setting category on deferred templates) also adds some risk of side effects elsewhere. B additionally covers the degenerate "./" case and flattens nested decoratorOwner chains at construction time; A's loop handles the chain equivalently. Tests are comparable in quality otherwise, with B also asserting that partialCached keys differ per directory. Docs are adequate in both. B wins on correctness.

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

44m 40s

Wall-clock time in the container

Full test suite

No new failures

961 passed · 1 skipped · 970 total

Contamination audit

Clean

No sign the agent saw the real fix

Patch size

224vs 204 merged

Changed lines, ours vs merged

Right now partial calls only supports path relative to layout/partials and themes/<THEME>/layouts/partials/*<PARTIALNAME> (taken from the documentation).

This is fine when we have few partials but can become a pain if we need to organize them in subdirectories.

What i propose is to add support for relative paths like in this example :

{{ partial "./foo" ... }}
{{ partial "../bah" ... }}

Why ?

Having this feature could be beneficial in a lot or ways :

  • it avoid us having to remember and write the full partial path when it's not needed (for example utility partials that are only called and only used by a on partial)
  • It could allow us to reorganize partials way more easily, as relative paths would full path independent

How to implement

If the path in a partial call starts with "./" or "../", it's a relative path. Otherwise it's an "absolute" path (relative to layout/partials).

I'm against adding the current directory of the current partial to the lookup search directly though, as theme and site authors currently assume this would call to the partial root directory. Perhaps we could add this to the future, if my proposal is adopted by the community.

The two patches

Our patch+224 −0
docs/content/en/functions/partials/Include.mdindex 58acbcc7f..591bf3a6f 100644@@ -62,6 +62,15 @@ Then, within the _partial_ template: <p>See <a href="{{ .page.RelPermalink }}">details.</a></p> ``` +Within a _partial_ template, a NAME beginning with `./` or `../` is resolved relative to the directory of the calling _partial_ template. Any other NAME is resolved relative to the `layouts/_partials` directory. For example, within `layouts/_partials/cards/list.html`:++```go-html-template+{{ partial "./card.html" . }}     {{/* layouts/_partials/cards/card.html */}}+{{ partial "../footer.html" . }}  {{/* layouts/_partials/footer.html */}}+```++Relative paths are not supported outside of _partial_ templates, and may not resolve to a path outside of the `layouts/_partials` directory. The same rules apply to [`partials.IncludeCached`](/functions/partials/includecached/).+ To return a value from a _partial_ template, it must contain only one `return` statement, placed at the end of the template:  ```go-html-templatetpl/partials/partials.goindex f0906fb83..ddd7fc518 100644@@ -20,6 +20,7 @@ import ( 	"errors" 	"fmt" 	"html/template"+	"path" 	"strings" 	"time" @@ -111,6 +112,10 @@ func (ns *Namespace) Include(ctx context.Context, name string, contextList ...an }  func (ns *Namespace) include(ctx context.Context, name string, dataList ...any) includeResult {+	name, err := resolveRelativeName(ctx, name)+	if err != nil {+		return includeResult{err: err}+	} 	v, err := ns.lookup(name) 	if err != nil { 		return includeResult{err: err}@@ -118,6 +123,41 @@ func (ns *Namespace) include(ctx context.Context, name string, dataList ...any) 	return ns.doInclude(ctx, "", v, dataList...) } +// resolveRelativeName resolves a partial name starting with "./" or "../"+// relative to the directory of the partial currently being executed.+// Other names are returned unchanged.+func resolveRelativeName(ctx context.Context, name string) (string, error) {+	if !strings.HasPrefix(name, "./") && !strings.HasPrefix(name, "../") {+		return name, nil+	}+	var (+		dir string+		ok  bool+	)+	cur := tpl.Context.CurrentTemplate.Get(ctx)+	if cur != nil && cur.Parent != nil && strings.HasPrefix(cur.Name(), tpl.HugoDeferredTemplatePrefix) {+		// Deferred templates are shared between owners with identical bodies,+		// so resolve relative to the template that called templates.Defer.+		cur = cur.Parent+	}+	if cur != nil {+		if ti, isTi := cur.CurrentTemplateInfoOps.(*tplimpl.TemplInfo); isTi {+			dir, ok = ti.PartialDir()+		}+	}+	if !ok {+		return "", fmt.Errorf("partial %q: relative partial paths are only supported when called from a partial", name)+	}+	resolved := path.Join(dir, name)+	if resolved == "." || resolved == ".." || strings.HasPrefix(resolved, "../") {+		return "", fmt.Errorf("partial %q: relative path resolves outside of the partials directory", name)+	}+	if resolved == dir {+		return "", fmt.Errorf("partial %q: relative path resolves to a directory, not a partial", name)+	}+	return resolved, nil+}+ func (ns *Namespace) lookup(name string) (*tplimpl.TemplInfo, error) { 	if strings.HasPrefix(name, "partials/") { 		// This is most likely not what the user intended.@@ -181,6 +221,10 @@ func (ns *Namespace) doInclude(ctx context.Context, key string, templ *tplimpl.T // Note that ctx is provided by Hugo, not the end user. func (ns *Namespace) IncludeCached(ctx context.Context, name string, context any, variants ...any) (any, error) { 	start := time.Now()+	name, err := resolveRelativeName(ctx, name)+	if err != nil {+		return nil, err+	} 	keyString := name 	if len(variants) > 0 { 		key := partialCacheKey{tpl/partials/partials_integration_test.goindex 72b5f62a5..723b4db3f 100644@@ -428,3 +428,142 @@ baseURL = 'http://example.com/'  	b.AssertFileContent("public/index.html", "42|") }++func TestIncludeRelativePath(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = 'http://example.com/'+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS", "page"]+-- layouts/home.html --+home: {{ partial "a/b/main.html" . }}|{{ partial "top.html" . }}+-- layouts/_partials/top.html --+top: {{ partial "./a/util.html" . }}+-- layouts/_partials/a/util.html --+a-util+-- layouts/_partials/a/b/main.html --+main: {{ partial "./util.html" . }}|{{ partial "../util.html" . }}|{{ partial "./c/deep" . }}|{{ partials.Include "../b/util.html" . }}|{{ partialCached "./util.html" . }}|{{ partials.IncludeCached "../util.html" . "v1" }}|{{ partial "util.html" . }}+-- layouts/_partials/a/b/util.html --+a-b-util+-- layouts/_partials/a/b/c/deep.html --+deep: {{ partial "../../util.html" . }}+-- layouts/_partials/util.html --+root-util+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"home: main: a-b-util|a-util|deep: a-util|a-b-util|a-b-util|a-util|root-util|top: a-util",+	)+}++func TestIncludeRelativePathCachedKeyIsResolved(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = 'http://example.com/'+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS", "page"]+-- layouts/home.html --+{{ partial "x/p.html" . }}|{{ partial "y/p.html" . }}+-- layouts/_partials/x/p.html --+{{ partialCached "./util.html" . }}+-- layouts/_partials/x/util.html --+x-util+-- layouts/_partials/y/p.html --+{{ partialCached "./util.html" . }}+-- layouts/_partials/y/util.html --+y-util+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html", "x-util\n|y-util")+}++func TestIncludeRelativePathInDecorator(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = 'http://example.com/'+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS", "page"]+-- layouts/home.html --+{{ partial "a/main.html" . }}+-- layouts/_partials/a/main.html --+{{ with partial "./wrap.html" . }}[{{ partial "./util.html" . }}]{{ end }}+-- layouts/_partials/a/wrap.html --+wrap({{ inner . }})+-- layouts/_partials/a/util.html --+a-util+-- layouts/_partials/wrap.html --+wrong-wrap+-- layouts/_partials/util.html --+wrong-util+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html", "wrap([a-util])")+}++func TestIncludeRelativePathErrors(t *testing.T) {+	t.Parallel()++	for _, test := range []struct {+		name   string+		home   string+		errMsg string+	}{+		{"outside", `{{ partial "p.html" . }}`, `partial "../util.html": relative path resolves outside of the partials directory`},+		{"notpartial", `{{ partial "./util.html" . }}`, `partial "./util.html": relative partial paths are only supported when called from a partial`},+		{"notpartialcached", `{{ partialCached "./util.html" . }}`, `partial "./util.html": relative partial paths are only supported when called from a partial`},+		{"directory", `{{ partial "a/q.html" . }}`, `partial "./": relative path resolves to a directory, not a partial`},+	} {+		t.Run(test.name, func(t *testing.T) {+			t.Parallel()+			files := `+-- hugo.toml --+baseURL = 'http://example.com/'+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS", "page"]+-- layouts/home.html --+` + test.home + `+-- layouts/_partials/p.html --+{{ partial "../util.html" . }}+-- layouts/_partials/util.html --+util+-- layouts/_partials/a/q.html --+{{ partial "./" . }}+-- layouts/_partials/a.html --+a+`+			b, err := hugolib.TestE(t, files)+			b.Assert(err, qt.IsNotNil)+			b.Assert(err.Error(), qt.Contains, test.errMsg)+		})+	}+}++func TestIncludeRelativePathInDefer(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+baseURL = 'http://example.com/'+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS", "page"]+-- layouts/home.html --+{{ partial "a/p.html" . }}|{{ partial "b/p.html" . }}+-- layouts/_partials/a/p.html --+{{ with (templates.Defer (dict "key" "a")) }}{{ partial "./util.html" . }}{{ end }}+-- layouts/_partials/b/p.html --+{{ with (templates.Defer (dict "key" "b")) }}{{ partial "./util.html" . }}{{ end }}+-- layouts/_partials/a/util.html --+a-util+-- layouts/_partials/b/util.html --+b-util+`+	b := hugolib.Test(t, files)+	b.AssertFileContent("public/index.html", "a-util\n|b-util")+}tpl/tplimpl/templatestore.goindex 4721c1f4a..0e6826050 100644@@ -263,6 +263,10 @@ type TemplInfo struct { 	// processing state. 	state          processingState 	isLegacyMapped bool++	// For internal partial decorator templates, the template that+	// contains the with block that the decorator was created from.+	decoratorOwner *TemplInfo }  func (ti *TemplInfo) SubCategory() SubCategory {@@ -362,6 +366,29 @@ func (t *TemplInfo) isProbablyTheSameIDAs(other identity.Identity) bool { 	return false } +// PartialDir returns the directory of this partial template relative to the+// partials root (e.g. "foo/bar" for "_partials/foo/bar/baz.html", "" for a+// partial at the root) and true.+// For internal partial decorator templates, the template owning the decorator is used.+// It returns false if this is not a partial template.+func (ti *TemplInfo) PartialDir() (string, bool) {+	if ti.decoratorOwner != nil {+		return ti.decoratorOwner.PartialDir()+	}+	if ti.category != CategoryPartial || ti.PathInfo == nil {+		return "", false+	}+	dir := path.Dir(ti.PathInfo.Path())+	prefix := "/" + containerPartials+	if dir == prefix {+		return "", true+	}+	if !strings.HasPrefix(dir, prefix+"/") {+		return "", false+	}+	return strings.TrimPrefix(dir, prefix+"/"), true+}+ // Implements the additional methods in tpl.CurrentTemplateInfoOps. func (ti *TemplInfo) Base() tpl.CurrentTemplateInfoCommonOps { 	return ti.basetpl/tplimpl/templatetransform.goindex dcb59abe7..6e67e846f 100644@@ -301,6 +301,11 @@ func (c *templateTransformContext) handleWithPartial(withNode *parse.WithNode) { 			c.err = fmt.Errorf("failed to find internal partial decorator template %q after insertion", internalPartialName) 			return 		}+		// Relative partial paths inside the with block resolve relative to the template containing it.+		ti.decoratorOwner = c.t+		if c.t.decoratorOwner != nil {+			ti.decoratorOwner = c.t.decoratorOwner+		}  		cc := newTemplateTransformContext(ti, c.store, c.lookupFn)  
Merged fix · PR #15376+200 −4
docs/content/en/functions/partials/Include.mdindex 58acbcc7f..d42dacce0 100644@@ -74,5 +74,29 @@ To return a value from a _partial_ template, it must contain only one `return` s {{ return $result }} ``` +## Relative paths++{{< new-in 0.167.0 />}}++Within a _partial_ template, a path that begins with `./` or `../` is resolved relative to the directory of the calling _partial_ template. For example, given this structure:++```tree+layouts/+└── _partials/+    ├── cards/+    │   ├── card.html+    │   └── image.html+    └── footer.html+```++The "card" _partial_ template can call its sibling and the "footer" _partial_ template like this:++```go-html-template+{{ partial "./image.html" . }}+{{ partial "../footer.html" . }}+```++Relative paths are only supported from within _partial_ templates. Calling `partial "./foo.html"` from any other template, or with a path that resolves outside the `_partials` directory, is an error.+ [`return`]: /functions/go-template/return/ [breadcrumb navigation]: /content-management/sections/#ancestors-and-descendantsdocs/content/en/functions/partials/IncludeCached.mdindex eea5751e8..a58ee53e9 100644@@ -20,6 +20,8 @@ The `partialCached` function can offer significant performance gains for complex > > Hugo renders pages in parallel, and will render the _partial_ template more than once with concurrent calls to the `partialCached` function. After Hugo caches the rendered _partial_ template, new pages entering the build pipeline will use the cached result. +Within a _partial_ template, a path that begins with `./` or `../` is resolved relative to the calling _partial_ template. See [`partials.Include`](/functions/partials/include/#relative-paths).+ Here is the simplest usage:  ```go-html-templatetpl/partials/partials.goindex f0906fb83..f27ba186e 100644@@ -111,6 +111,10 @@ func (ns *Namespace) Include(ctx context.Context, name string, contextList ...an }  func (ns *Namespace) include(ctx context.Context, name string, dataList ...any) includeResult {+	name, err := ns.deps.TemplateStore.ResolvePartialName(ctx, name)+	if err != nil {+		return includeResult{err: err}+	} 	v, err := ns.lookup(name) 	if err != nil { 		return includeResult{err: err}@@ -181,6 +185,10 @@ func (ns *Namespace) doInclude(ctx context.Context, key string, templ *tplimpl.T // Note that ctx is provided by Hugo, not the end user. func (ns *Namespace) IncludeCached(ctx context.Context, name string, context any, variants ...any) (any, error) { 	start := time.Now()+	name, err := ns.deps.TemplateStore.ResolvePartialName(ctx, name)+	if err != nil {+		return nil, err+	} 	keyString := name 	if len(variants) > 0 { 		key := partialCacheKey{tpl/partials/partials_integration_test.goindex 72b5f62a5..477eb55ee 100644@@ -428,3 +428,134 @@ baseURL = 'http://example.com/'  	b.AssertFileContent("public/index.html", "42|") }++// See issue 15373.+func TestIncludeRelativePath(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]+-- layouts/home.html --+{{ partial "a/b/main.html" . }}+{{ partial "c/main.html" . }}+{{ partial "inline.html" . }}+{{ define "_partials/a/inline.html" }}inline:{{ partial "./helper.html" . }}{{ end }}+-- layouts/_partials/inline.html --+{{ partial "a/inline.html" . }}+-- layouts/_partials/a/b/main.html --+same:{{ partial "./helper.html" . }}+sub:{{ partial "./sub/helper.html" . }}+parent:{{ partial "../helper.html" . }}+root:{{ partial "../../root.html" . }}+cached:{{ partialCached "./cached.html" . }}+dynamic:{{ partial (printf "./%s.html" "helper") . }}+include:{{ partials.Include "./helper.html" . }}+-- layouts/_partials/a/b/helper.html --+a/b/helper+-- layouts/_partials/a/b/sub/helper.html --+a/b/sub/helper+-- layouts/_partials/a/b/cached.html --+a/b/cached+-- layouts/_partials/a/helper.html --+a/helper+-- layouts/_partials/root.html --+root+-- layouts/_partials/c/main.html --+cached:{{ partialCached "./cached.html" . }}+-- layouts/_partials/c/cached.html --+c/cached+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html",+		"same:a/b/helper",+		"sub:a/b/sub/helper",+		"parent:a/helper",+		"root:root",+		"cached:a/b/cached",+		"dynamic:a/b/helper",+		"include:a/b/helper",+		"cached:c/cached",+		"inline:a/helper",+	)+}++func TestIncludeRelativePathInDecoratorInner(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]+-- layouts/home.html --+{{ partial "a/main.html" . }}+-- layouts/_partials/a/main.html --+{{ with partial "b/wrapper.html" . }}{{ partial "./helper.html" . }}{{ end }}+-- layouts/_partials/a/helper.html --+a/helper+-- layouts/_partials/b/wrapper.html --+wrapper:{{ inner . }}+-- layouts/_partials/b/helper.html --+b/helper+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html", "wrapper:a/helper")+}++func TestIncludeRelativePathNotFromPartial(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]+-- layouts/home.html --+{{ partial "./helper.html" . }}+-- layouts/_partials/helper.html --+helper+`++	b, err := hugolib.TestE(t, files)++	b.Assert(err, qt.ErrorMatches, `(?s).*relative partial path "./helper.html" can only be used from within a partial.*`)+}++func TestIncludeRelativePathOutsidePartials(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]+-- layouts/home.html --+{{ partial "a/main.html" . }}+-- layouts/_partials/a/main.html --+{{ partial "../../helper.html" . }}+-- layouts/_partials/helper.html --+helper+`++	b, err := hugolib.TestE(t, files)++	b.Assert(err, qt.ErrorMatches, `(?s).*relative partial path "../../helper.html" in "_partials/a/main.html" resolves outside the partials directory.*`)+}++func TestIncludeRelativePathInDeferredBlock(t *testing.T) {+	t.Parallel()++	files := `+-- hugo.toml --+disableKinds = ["section", "taxonomy", "term", "sitemap", "RSS"]+-- layouts/home.html --+{{ partial "a/main.html" . }}+-- layouts/_partials/a/main.html --+{{ with (templates.Defer (dict "key" "a")) }}deferred:{{ partial "./helper.html" . }}{{ end }}+-- layouts/_partials/a/helper.html --+a/helper+`++	b := hugolib.Test(t, files)++	b.AssertFileContent("public/index.html", "deferred:a/helper")+}tpl/tplimpl/templatestore.goindex 4721c1f4a..b1aed169f 100644@@ -249,6 +249,9 @@ type TemplInfo struct { 	// The base template used, if any. 	base *TemplInfo +	// For partial decorator inner templates, the template the inner block was defined in.+	decoratorOwner *TemplInfo+ 	// The descriptior that this template represents. 	D TemplateDescriptor @@ -636,6 +639,31 @@ func (s *TemplateStore) LookupPartial(pth string) *TemplInfo { 	return ti } +// ResolvePartialName resolves partial names starting with "./" or "../"+// relative to the directory of the calling partial.+func (s *TemplateStore) ResolvePartialName(ctx context.Context, name string) (string, error) {+	if !strings.HasPrefix(name, "./") && !strings.HasPrefix(name, "../") {+		return name, nil+	}+	cur := tpl.Context.CurrentTemplate.Get(ctx)+	if cur == nil {+		return "", fmt.Errorf("relative partial path %q can only be used from within a partial", name)+	}+	ti := cur.CurrentTemplateInfoOps.(*TemplInfo)+	for ti.decoratorOwner != nil {+		ti = ti.decoratorOwner+	}+	if ti.category != CategoryPartial {+		return "", fmt.Errorf("relative partial path %q can only be used from within a partial, called from %q", name, ti.Name())+	}+	dir := strings.TrimPrefix(strings.TrimPrefix(ti.PathInfo.Dir(), "/"+containerPartials), "/")+	resolved := path.Join(dir, name)+	if resolved == ".." || strings.HasPrefix(resolved, "../") {+		return "", fmt.Errorf("relative partial path %q in %q resolves outside the partials directory", name, ti.Name())+	}+	return resolved, nil+}+ func (s *TemplateStore) LookupShortcodeByName(name string) *TemplInfo { 	name = strings.ToLower(name) 	ti, _ := s.shortcodesByName.Get(name)@@ -939,10 +967,12 @@ func (t *TemplateStore) addDeferredTemplate(owner *TemplInfo, name string, n *pa 	}  	t.templatesByPath.Set(name, &TemplInfo{-		Fi:       owner.Fi,-		PathInfo: owner.PathInfo,-		D:        owner.D,-		Template: templ,+		Fi:             owner.Fi,+		PathInfo:       owner.PathInfo,+		D:              owner.D,+		Template:       templ,+		category:       owner.category,+		decoratorOwner: owner.decoratorOwner, 	})  	return niltpl/tplimpl/templatetransform.goindex dcb59abe7..3c37ea6ef 100644@@ -301,6 +301,7 @@ func (c *templateTransformContext) handleWithPartial(withNode *parse.WithNode) { 			c.err = fmt.Errorf("failed to find internal partial decorator template %q after insertion", internalPartialName) 			return 		}+		ti.decoratorOwner = c.t  		cc := newTemplateTransformContext(ti, c.store, c.lookupFn)