Given the following front matter:
[[book]]
title = "Dog"
price = 12
[[book]]
title = "Ape"
price = 20
[[book]]
title = "Cat"
price = 32
And code:
{{range .Params.book}}
<tr>
{{range .}}
<td>
{{.}}
</td>
{{end}}
</tr>
{{end}}
Gives this output:
12: Dog
20: Ape
32: Cat
But I’d like the default order. Desired output:
Dog: 12
Ape: 20
Cat: 32
How do I do this please?
What do you mean by “default” order?
{{ range .Params.book }}
{{ range $key, $value := . }}
{{ $key }} : {{ $value }}
{{ end }}
{{ end }}
By default order, I mean the order as specified in front matter. In this case: title followed by price.
Using your code, you get the following:
price : 12 title : Dog
price : 20 title : Ape
price : 32 title : Cat
Which is not what I’m after, as the order is incorrect: price, then title.
My use case is that I’m creating a table, and the headings are title, then price. By using your code, or my original one, you get the wrong order.
Not sure if it’s linked to this .
{{ range .Params.book }}
{{ .title }}: {{ .price }}<br>
{{ end }}
Thank you.
This won’t work as I’m creating a table. Each book needs to have it’s own row, <tr>
, with each value having it’s own data cell, <td>
.
I don’t see why the short example can’t be amended to look like
{{ range .Params.book }}
<tr><td>{{ .title }}:</td><td>{{ .price }}</td></tr>
{{ end }}
Or do you mean something else entirely?
That works. It’s just that I plan on having more values and so I’ll be duplicating code for each parameter. Every time I add a value, I need to add another <td>
. I was trying to keep avoid having to repeat myself. Does that make sense?
regis
June 26, 2021, 5:38pm
8
I’ve been there before. Go orders keys by alphanum and there’s no way around it.
If you you know your keys you can do the following:
{{ range $book := .books }}
<tr>
{{ range slice "title" "price" "other" }}
{{ with index $book . }}
<td>{{ . }}</td>
{{ end }}
{{ end }}
</tr>
{{ end }}
1 Like
Sir, this belongs to you →
system
Closed
June 28, 2021, 6:58pm
11
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.