Resize image given an url from partial

Hi,

I want to implement last articles on mi blog index.html with and image, and I have in front matter for each post a param:

img: img/test.png

I can show the image with this code:

{{ with .Site.GetPage "/blog" }}
    {{ range first 4 .Pages }}
    <div>
        {{ $urlImg:= "" }}
        {{ $permalink := .Permalink }}
        {{ with .Params.img }}
        {{ $urlImg = (printf "%s%s" $permalink .) }}
        {{ end }}
        <a href="{{.Permalink}}">
            <img src="{{$urlImg}}">
            <span>{{.Title}}</span>
        </a>
    </div>
{{ end }}

I have tried with this partial:

{{ partial "img.html" (dict "context" . "src" $urlImg ) }}

And trying to show the width of the image in the partial, but it doesn´t work.

{{ $src := .context.Page.Resources.GetMatch (printf "*%s*" .src) }}
{{ $src.Width }}

Any help please? I am new in Hugo. I have a shortcode for responsive images, but I can´t get the same in a partial.

Thanks a lot, best regards.

Hi,

I’m just guessing here, but I think your issue is with the path you are passing to .GetMatch. It looks like you are passing the full rendered URL of the img, ie yoursite.com/blog/foo/bar.png, which works for the img src attribute.

However .GetMatch, as a Page Resources method, is relative to the .Page object.

See this example in the docs. If you have a Page Bundle at content/blog/foo/index.md , the example image above would be located at content/blog/foo/images/sunset.jpg, in the specific example.

Thanks for the links, I could correct it and make it work:

{{ with .Site.GetPage "/blog" }}
{{ range first 4 .Pages }}
<article>
    <a class="hover:text-green-500" href="{{.Permalink}}">
        {{ $contextBlog := . }}
        {{ with .Params.img }}
            {{ $resources := $contextBlog.Resources.Match . }}
            {{ $cover := index ($resources) 0 }}
            {{ with $cover.Width }}
                {{ $img := $cover }}
                {{ if ge $cover.Width "640" }}
                    {{ $img = $cover.Resize "640x" }}
                {{ end }}
                {{ partial "img.html" (dict "context" . "img" $img) }}
            {{ end }}
        {{ end }}
        <span>{{.Title}}</span>
    </a>
</article>
{{ end }}