Accessing .Params within with statement

Hello all:

Here is my Hugo environment:

❯ hugo env
hugo v0.135.0+extended darwin/arm64 BuildDate=2024-09-27T13:17:08Z VendorInfo=brew
GOOS="darwin"
GOARCH="arm64"
GOVERSION="go1.23.1"
github.com/sass/libsass="3.6.6"
github.com/webmproject/libwebp="v1.3.2"

I am attempting to access frontmatter data within a “with” statement.
Here is an excerpt from a post’s frontmatter:

---
params:
  cover:
    src: images/cover.webp
    title: Photo by Sara Kurfeß on Unsplash
---

In a partial, I am trying to get params.cover.title (which this example does not work)

{{ with .Resources.GetMatch .Params.cover.src }}
    {{ with .Crop "800x341" }}
        <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ .Params.cover.title }}" />
    {{ end }}
{{ end }}

Is creating a variable for the title outside of the “with” statements the Hugo way?

{{ $imageTitle := .Params.cover.title }}
{{ with .Resources.GetMatch .Params.cover.src }}
    {{ with .Crop "800x341" }}
        <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ $imageTitle }}" />
    {{ end }}
{{ end }}

It works, but I am looking for validation if this is the correct way, as I am only a few days into Hugo.

Thank you

https://gohugo.io/functions/go-template/with/

{{ with $var := 42 }}
  {{ . }} → 42
  {{ $var }} → 42
{{ end }}

With that simple partials, where you pass a Page {{ partial "NAME" PAGE_OBJECT }} you may use the $ to access the context passed to the template. $.Params

The . in a with/range is always rebound to the current level.

So that would be:

## here . and $ are same
{{ with .Resources.GetMatch .Params.cover.src }}
    ## here the . is the result of .Resources.GetMatch
    {{ with .Crop "800x341" }}
        ## here the . is the result of .Crop
        ## so we have to use the $ instead
        <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="{{ $.Params.cover.title }}" />
    {{ end }}
{{ end }}

see Template Context - The dot and the dollar

Thank you!

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