Hi
Let say I have to different params in my front matter which I will implement on every single page that have FAQ menu (the FAQ could be different in every page so I create this params)
ask:
- A
- B
- C
- D
answer:
- 1
- 2
- 3
- 4
How can I range both of params in the same time with output like below
<li>A1</>
<li>B2</>
<li>C3</>
<li>D4</>
as a temporary workaround I’m using nested like this
faq:
- ask: A
answer: 1
{{ range $faq := .Params.faq }}
<li>{{$faq.ask}}</li>
<li>{{$faq.answer}}</li>
{{end}}
as simple as that and work like a charm, but since the plan is using Forestry this workaround can be hard to implement (as far as I know)
Sorry if the title and this question is confusing
any idea?
Thank You
1 Like
Hi,
You could try range
over one array and then use the index
to access the other array, maybe something like this:
{{ $arr1 := (slice "1" "2" "3" "4") }}
{{ $arr2 := (slice "A" "B" "C" "D") }}
{{ range $i, $e := $arr1 }}
{{ index $arr2 $i }}{{ $e }}
{{ end }}
should give you something like A1 B2 C3 D4
.
Thanks, I tried this
{{ $arr1 := (slice .Params.ask) }}
{{ $arr2 := (slice .Params.answer) }}
{{ range $i, $e := $arr1 }}
<li>{{ index $arr2 $i }}{{ $e }}<li>
{{ end }}
the output is empty nothing get index, did I missed something?
Hi,
sorry, you don’t have to use slice
here, I used it to initialise the values for arrays $arr1
and $arr2
.
Basically replace $arr1
and $arr2
with whatever your arrays are.
{{ $arr1 := .Params.ask }}
{{ $arr2 := .Params.answer }}
{{ range $i, $e := $arr1 }}
<li>{{ index $arr2 $i }}{{ $e }}<li>
{{ end }}
or even
{{ range $i, $e := .Params.ask }}
<li>{{ index .Params.answer $i }}{{ $e }}<li>
{{ end }}
if that works
both of them have empty output, may I know what is $i and $e mean?
I use $i
and $e
as shorthand for $index
and $element
as used in the example I linked above.
I tried to replicate the scenario you described and created a page with the frontmatter as you have in your original post. In single.html
I have the following:
{{ if isset .Params "ask" }}
{{ $arr1 := .Params.ask }}
{{ $arr2 := .Params.answer }}
{{ range $i, $e := $arr1 }}
{{ index $arr2 $i }}{{ $e }}
{{ end }}
{{ end }}
and that renders 1A 2B 3C 4D
for me. You may have to share your repo in case it’s something else that is not working.
thanks for pinting me about $i and $e
You are correct I tried those code in different content section and it works, but the strange thing is why it doesn’t work in in my project section
I suspect there’s some bad code of mine in my single project template or else in my front matter
Will get back after I find out the problem thank you