How to limit range to first 1

Hey, I’m new to this language. How can I limit this to only the first string ($image) in the array ($images)? I have tried adding first 1 in different ways, but it is not working for me. Many thanks for help!

This works but shows all images from array:

{{ if isset .Params "images" }}
    {{ range $images := .Params.images }}
    {{ $image := resources.Get $images }}
      {{with $image }}
        <img src="{{ ($image.Resize "900x").RelPermalink }}">
      {{ end }}
    {{ end }}
  {{ end }}

I have tried adding β€œfirst 1” for example here:

{{ if isset .Params "images" }}
    {{ range first 1 $images := .Params.images }}
    {{ $image := resources.Get $images }}
      {{with $image }}
        <img src="{{ ($image.Resize "900x").RelPermalink }}">
      {{ end }}
    {{ end }}
  {{ end }}

Use the index function.

{{ with .Params.images }}
  {{ with index . 0 }}
    {{ with resources.Get . }}
      <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
    {{ else }}
      {{ errorf "Unable to find image %s" . }}
    {{ end }}
  {{ end }}
{{ end }}

If you use page resources instead of global resources, you wouldn’t need any front matter.

content/
β”œβ”€β”€ post/
β”‚   └── test/
β”‚       β”œβ”€β”€ a.jpg
β”‚       β”œβ”€β”€ b.jpg
β”‚       └── index.md
└── _index.md
{{ with .Resources.ByType "image" }}
  {{ with index . 0 }}
    <img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
  {{ end }}
{{ end }}
4 Likes

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