With the following front matter:
+++
author = ["author1", "author2"]
title = "Book Title"
+++
I would like to achieve this structure:
"title" : "Book Title",
"author": {
"name": "Author1"
},
"author": {
"name": "Author2"
}
I’m having difficulties with ranging over the author
to create two separate author sections.
My code in list.html
:
{{range $i, $e := where .Pages "Section" "books"}}
{{- if $i }}, {{end}}
"title" : "{{.Title}}",
{{range $i, $e := .Params.author}}
{{- if $e }}, {{end}}
"author": {
"name":"{{$e}}"
}
{{end}}
{{end}}
This gives:
"title" : "Book Title",
"author": {
"name": "Author1, Author2"
}
bep
January 13, 2019, 10:20pm
2
I suspect that you could do this simpler by something ala (typed and untested):
{{ $book := dict "title" .Title "author" .Params.author }}
{{ $bookJSON := $book | jsonify }}
pancake
January 13, 2019, 10:29pm
3
Thanks, that code snippet is helpful. But, it doesn’t solve the problem.
It gives the following output:
{"author":["DHH, Jason Fried"],"title":"ReWork"}
{"author":["Yuval Noah Harari"],"title":"Sapiens"}
For ReWork, I’m looking for the output to be as shown in the initial post, the authors to be separated. I’ll continue working on this. Appreciate the help.
bep
January 13, 2019, 11:31pm
4
What is your “full code” with my suggested way? I say this because I think you have a “range too many”.
pancake
January 13, 2019, 11:40pm
5
Complete code in template list.html
{{range where (where .Pages "Section" "books") "Layout" "ne" "keyword"}}
{{$book := dict "title" .Title "author" .Params.author}}
{{$bookJSON := $book | jsonify}}
{{$bookJSON}}
{{end}}
bep
January 13, 2019, 11:46pm
6
Yes, OK, sorry, I misread your original question. I will have to get back to you on this. I’m writing this in bed, dead tired …
pancake
January 13, 2019, 11:47pm
7
No worries. Again appreciate the help. I’m beat too so I’m going to revisit this tomorrow. Thanks a bunch.
This is the solution I’ve come up with. Let me know if there is a better way.
{{range $i, $e := where .Pages "Section" "books"}}
{{- if $i }}, {{end}}
"title" : "{{.Title}}",
{{range $i, $e := .Params.author}}
{{- if $i }}, {{end}}
"author": {
"name":"{{$e}}"
}
{{end}}
{{end}}
This is actually identical to the code I provided in my original post. The mistake I did previously was use {{if $e}}
instead of {{if $i}}
.