Is this the correct way to define multiple custom variables?

Or can they be condensed further?

    {{- $imgURL := "" }}
    {{- $width := "" }}
    {{- $height := "" }}
    {{- $mediaType := ""}}
    {{- if and (eq .Params.layout "news") (eq .Kind "page") }}
    {{- with .Parent.Resources.GetMatch "thumbnail.*" }}
    {{- $imgURL = .Permalink }}
    {{- $width = .Width }}
    {{- $height = .Height }}
    {{- $mediaType = .MediaType.Type }}
    {{- end }}
    {{- else }}
    {{- with or (.Resources.GetMatch "thumbnail.*") (.Resources.GetMatch "thumbnail.fr.*") }}
    {{- $imgURL = .Permalink }}
    {{- $width = .Width }}
    {{- $height = .Height }}
    {{- $mediaType = .MediaType.Type }}
    {{- end }}
    {{- end -}}

Is this a multilingual site? Something like…

content/
β”œβ”€β”€ posts/
β”‚   β”œβ”€β”€ post-1/
β”‚   β”‚   β”œβ”€β”€ index.fr.md
β”‚   β”‚   β”œβ”€β”€ index.md
β”‚   β”‚   β”œβ”€β”€ thumbnail.fr.jpg
β”‚   β”‚   └── thumbnail.jpg
β”‚   β”œβ”€β”€ _index.fr.md
β”‚   └── _index.md
β”œβ”€β”€ _index.fr.md
└── _index.md

And is your code accurate? Because you are currently retrieving the same resource regardless of the param value.

The code is similar to this one. But I am defining the variables before using them. Open graph for images in multipage posts - #4 by jmooring. I have edited the code in my first comment.

Please confirm one way or the other.

I can’t tell if this is a reference to an asset for a particular language, or if it is something else:

(.Resources.GetMatch "thumbnail.fr*")

Yes. Multilingual. Instead of multipage, my layout I renamed to news. Same implementation though.

{{ $r := "" }}
{{ if and (eq .Params.layout "news") (eq .Kind "page") }}
  {{ with .Parent.Resources.GetMatch "thumbnail.*" }}
    {{ $r = . }}
  {{ end }}
{{ else }}
  {{ with .Resources.GetMatch "thumbnail.*" }}
    {{ $r = . }}
  {{ end }}
{{ end }}

Now that you have the Resource object in $r, just use:

{{ $r.Permalink }}
{{ $r.Width }}
{{ $r.Height }}
{{ $r.MediaType.Type }}

or

{{ with $r }}
  <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}

Note that I replaced this:

{{- with or (.Resources.GetMatch "thumbnail.*") (.Resources.GetMatch "thumbnail.fr.*") }}

with this:

{{ with .Resources.GetMatch "thumbnail.*" }}

In a multilingual site, page resources are shared unless language-specific.

1 Like

Yes, my resources are language specific. I saw if I do thumbnail.* then thumbnail.fr.* is ignored

I can’t reproduce that behavior, so maybe something specific to your site/config.

I tested this some time back with an older Hugo version (around Feb). So, I might have made a mistake somewhere.

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