Can't embed image in the template

Hi everyone!

I building my first Hugo website from the scratch and currently trying to embed image in the template of the page, so that I could add its path via frontmatter parameters, however, I get error (below).

To add image I am using code from a theme that I used before, it looks like I can re-use it but I don’t get why it doesn’t work.


execute of template failed at <add `assets/` .image>: error calling add: can’t apply the operator to the values 


{{range .component}}

<div class = "max-w-[18rem]">
    {{ if fileExists (add `assets/` .image) }}
    {{$img:= resources.Get (.image) }}
    {{$img:= $img.Resize "300x webp"}}
    <img loading="lazy" decoding="async" src="{{$img.RelPermalink}}" alt="">
{{ end }}


    - image: "images/diff_icon_04.webp"

Any help is appreciated, thanks!

If the assets directory in the root of your project looks like this:

└── images/
    ├── a.jpg
    ├── b.jpg
    └── c.jpg

And your front matter looks like this:

title: Post 1
date: 2021-01-01T00:00:00-00:00
draft: false
  - image: images/a.jpg
  - image: images/b.jpg
  - image: images/c.jpg

Then you can render the images like this:

{{ range .Params.component }}
  {{ with resources.Get .image }}
    {{ with .Resize "300x webp" }}
      <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
    {{ end }}
  {{ end }}
{{ end }}

You do not need a file existence check.

Thanks @jmooring !
It worked.

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