Scratch scoping to customize metadata partial in post list and post single

Hi all

I have a post metadata bar in a partial partials/post_meta.html that appears under the post title in _default/single.html. I also want to use the same partial in post lists on index.html and section/post.html. However, I need to simplify the contents of the metadata partial in cases where it appears on one of these two list pages. Therefore, I considered Scratch as a potential solution.

The code works fine (simplifying the metadata partial only on the homepage and not on the single page) until I add Scratch to the section/post.html, when the partial now thinks on every page that it’s in a list.

Code is below, any ideas - I guess it’s a scoping issue, or perhaps there’s a better way to achieve this without Scratch?



            {{ range first 5 (where .Data.Pages "Type" "post") }}
                {{ .Scratch.Add "is_list" 1 }}
                {{ partial "post_meta" . }}
            {{ end }}


{{ $is_list := .Scratch.Get "is_list" }}

{{ if $is_list }}
<a href="{{ .Permalink }}">Read</a>
brief post metadata
{{ else }}
full post metadata
{{ end }}


{{ partial "post_meta" . }}


     {{ range .Data.Pages.GroupByDate "2006" }}
                <h3>{{ .Key }}</h3>
                    {{ range .Pages.ByDate.Reverse }}
                    {{ .Scratch.Add "is_list" 1 }}{{ partial "post_meta" . }}
                    {{ end }}
        {{ end }}

I haven’t looked closely (I guess this is about parallelism), but this looks like a funky use of Scratch. Have a look at dict.

1 Like

Thank you very much @bep, dict is a much cleaner solution and less hacky :slightly_smiling:

For the record, I am now calling the partial using the dict solution with:

{{ partial "post_meta" (dict "content" . "is_list" 0) }}

for calls from the detail page single.html, and the following for calls from list pages:

{{ partial "post_meta" (dict "content" . "is_list" 1) }}

And the partial post_meta is essentially like:

{{ $is_list := .is_list }}
{{ if $is_list }}
<a class="btn btn-primary btn-xs" href="{{ .content.Permalink }}">Details</a>
{{ end }}
...other stuff here...

The solution will be added soon to the Academic theme if anyone is interested to see the full implementation: .