Range from two arrays

Hey guys!
in /content/blog/my-post.md I have two arrays

FAQquestion: ["question about something", "second question", "third Q"]
FAQanswer: ["answer no 1", "another answer", "answer no 3" ]

I want to add this to html head to have something like this

<script type="application/ld+json">
  {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    "mainEntity": [
      {
        "@type": "Question",
        "name": "{{ .FAQquestion}}",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "Answer is: {{ .FAQanswer }} "
        }
      },
      {
        "@type": "Question",
        "name": "{{ .FAQquestion }}",
        "acceptedAnswer": {
          "@type": "Answer",
          "text": "{{ .FAQanswer }}"
        }
      }
    ]
  }
  </script>

How I should write a loop to get values from two arrays? I tried a lot of combinations but I can’t do it.

It will be easier if you restructure your data.

front matter

faqs:
  - q: question 1
    a: answer 1
  - q: question 2
    a: answer 2

template

{{ range .Params.faqs }}
  Question: {{ .q }}<br>
  Answer: {{ .a }}<br><br>
{{ end }}
1 Like

Huh, so easy :grinning: thanks it’s working! But will leave open for a while this topic, I am curious how to do it another way :slight_smile:

The other way is messy:

{{ if and .Params.FAQquestion .Params.FAQanswer }}
  {{ if eq (len .Params.FAQquestion) (len .Params.FAQanswer) }}
    {{ range seq 0 (sub (len .Params.FAQquestion) 1) }}
      Question: {{ index $.Params.FAQquestion . }}<br>
      Answer: {{ index $.Params.FAQanswer . }}<br><br>
    {{ end }}
  {{ else }}
    {{ errorf "There must be an answer for each question." }}
  {{ end }}
{{ end }}

See my previous comment.

You could also do something ala:

{{ $questions := slice "question about something" "second question" "third Q" }}
{{ $answers := slice  "answer no 1" "another answer" "answer no 3"  }}
  
{{ range $i, $e := $questions }}
Question: {{ . }}| Answer: {{ index $answers $i }}
{{ end }}

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