Share a partial between a single page and a summary view

I’m trying to share a partial between a single page and a summary view. In the single page I need to use h1 for the title and h2 when the same page is shown in a (summary) list. Therefor I need to distinguish where the page is used. the .Kind and .Type and .IsPage always show the same value.

So how can I distinguish where the page is show/rendered?

Pseudo templates:

header.html

{{ if SOMECOMPARISON }}<h1>{{ else }}<h2>{{ end }}
  {{ .Title }}
{{ if SOMECOMPARISON }}</h1>{{ else }}</h2>{{ end }}

single.html

{{ partial header . }}
{{ .Content }}

list.html

<h1>{{.Title}}<h1>
{{ range ...}}
{{ render "summary.html" . }}
{{ end}}

summary.html

{{ partial header . }}
{{.Summary}}

Details

That is correct. Within the range, the context (the dot) represents the page within the current range iteration, not the page doing the ranging. You need some context for your context.

You can do this when calling a partial by doing something like this:

{{ partial "my-partial.html" (dict "page" . " "someString" "bar") }}
{{ partial "my-partial.html" (dict "page" . " "someBoolean" true) }}

Then access those values within the partial:

{{ .page.Title }}
{{ .page.RelPermalink }}
{{ .someString }}
{{ .someBoolean }}

However, in addition to partials you are using content views, and .Render does not take any arguments (your pseudo code is incorrect). This issue, specifically this comment, speaks to the limitation.

Option 1

Convert your content view (summary.html) into a partial, and pass additional arguments as shown above.

Option 2

Use a page-level .Scratch.

layouts/_default/list.html

{{ range .Pages }}
  {{ .Scratch.Set "withinRangeLoop" true}}
  {{ .Render "summary" }}
{{ end }}

layouts/partials/header.html

{{ if .Scratch.Get "withinRangeLoop" }}
  <h2><a href="{{ .RelPermalink }}">{{ .Title }}</a> H2</h2>
{{ else }}
  <h1><a href="{{ .RelPermalink }}">{{ .Title }}</a> H1</h1>
{{ end }}

Option 3 / Recommendation

Do less abstraction. While DRY/abstraction is generally beneficial, there are situations where the cost/debt incurred exceeds the benefit.

1 Like

Thanks for those recommendations. I think that #3 would be the best option for this specific case but I was also asking because I’m using this to learn Hugo.

I have implemented a solution using Scratch for now and will see where that brings me.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.