Using a front matter variable to index an array

Is it possible to pass a variable (from front matter) as the index value of an array?

I love that index $array 0 gets the array value at position 0. But when I replace the number (zero “0”, in this case) with a variable pulled from front matter, it errors with cannot index slice/array with nil.

Am I missing something basic here? Is there a way to pass in a front matter variable into INDEX?

Front Matter key-value pair in question in:
testimonialNumber = 0

The template code is:

 {{/*  Get all testimonials from Site CONFIG  */}}
{{ $testimonials := ( .Site.Params.testimonials) }}

 {{/*  Get a single number from the page's front matter  */}}
{{ $n := .Params.testimonialNumber }}

 {{/*  Cannot seem to pass in $n as the index value. How to pass in a number as a variable  */}}
{{ $singleTestimonial := index $testimonials $n }}

<div class="testimonial-sb">
     {{ $n }} -- <!-- testing the output value from front matter -->
    {{$singleTestimonial }}
</div>

Your problems is most likely that you have some pages without that param. What you can do is:

 {{/*  Get a single number from the page's front matter  */}}
{{ with .Params.testimonialNumber }}
{{ $singleTestimonial := index $testimonials . }}

<div class="testimonial-sb">
    {{$singleTestimonial }}
</div>
{{ end }}

Thank you for the fast reply.

Still not working for me. An error evaluating the index. I’ll put it aside for now and come back to with a clear head tomorrow and see if I can make more progress.

This error:

error calling index: cannot index slice/array with nil

is thrown because one or more of your content pages does not contain the testimonialNumber parameter in frontmatter.

In most cases you can wrap your code in a with or if conditional to check for an empty value. In this particular case, you cannot use either with or if because zero is an “empty” value:

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

So, you’ll need to wrap your code with isset.

{{ if isset .Params "testimonialnumber" }}
  {{ index site.Params.testimonials .Params.testimonialNumber }}
{{ end }}

Please note that the .Params key must be written in lowercase when using isset.

2 Likes

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