How <range> in <if>


#1

Hello,

How can i range in a conditionnal array ?

Here my code where I filter the results of the table by city

{{ $city := .Params.cityName }}
{{ range := .Site.Data.petiteannonce }}
{{ $cityName := .cityName }}
{{ if eq $city $cityName }}

but i just want the first three results.
I’ve tried with {{ range $index, $element := .Site.Data.petiteannonce }} but you know why :slight_smile:

thank you for your help


#2

Try the following:

{{ range := .Site.Data.petiteannonce }}
{{ if .cityName | eq .Params.cityName }}
// do something
{{ end }}
{{ end }}

#3

To be more precise (excuse my french :slight_smile: ) my first block of code is correct but i have all the result.
My issue is i just want the first 3 elements like {{ range first 3 }}


#4

Then try the following:

{{ $cities := where .Site.Data "petiteannonce" "eq" .Params.cityName }}
{{ range first 3 $cities }}
// do something
{{ end }}
{{ end }}

where allows you to filter a collection, e.g. with the equal operator (here eq).
I haven’t tested the code above but it should direct you in the right direction.


#5

For now I have

<first 3 $cities>: error calling first: can't iterate over map[string]interface {}

#6

Could you post an excerpt of your JSON?


#7

Traveling and on phone, so preemptive apologies @digitalcraftsman and @jonathanulco , but can the above be put into a one-liner:

{{ range first 3 (where .Site.Data.petiteannonce "eq" .Params.cityName) }}
Your code
{{ end }}

#8

Here an excerpt of the jSon https://pastebin.com/0h3m3T3R
and there’s 9 Bordeaux for your test :wink:


#9

Please share a pretty printed version of the JSON next time. Otherwise it’s hard to read. :wink:

I guess .Site.Data.petiteannonce equals the posted array of objects, right?

Give this a try:

{{ range first 3 (where .Site.Data.petiteannonce  "cityName" "eq" .Params.cityName) }}
Your code
{{ end }}

Somehow you have to compare the attribute cityName of the objects with .Params.cityName


#10

/bow @digitalcraftsman,
thanks you !