idarek
August 17, 2022, 6:00pm
1
Hi,
I got a simple code like that which is a part of Schema script <script type="application/ld+json">
[
{{ $counter := 0 }}
{{ range .Paginator.Pages }}
{{ $counter = add $counter 1 }}
{
"name": {{ .Title }},
"id": {{ $counter }}
}
{{ end}}
]
The problem is
when is single element, last }
is without comma ,
.
when is multiple items, after each }
there shall be comma ,
apart of last, like below.
[
{
"name": "First",
"id": 1
},
{
"name": "Second",
"id": 2
},
{
"name": "Third and last",
"id": 3
}
]
How to form something like
{{ if eq $counter 1 }} {{ else if last $counter }} {{ else }} , {{ end }}
ps. max $counter is equal value in config.toml
and paginate = 16
but can be less than that.
Thank you in advance.
Look simple but struggle to bite that.
I will share my output in Tips & Tricks here on what I am working on when finalised as it may be helpful for others.
{{ $s := slice "a" "b" "c" }}
{{ range $k, $_ := $s }}
{{ if $k }}
,
{{ end }}
{{ . }}
{{ end }}
idarek
August 17, 2022, 6:28pm
3
Thanks,
is it possible to use slice with range where
?
Here is code
<script type="application/ld+json">
{
"@context":"https://schema.org",
"@type":"ItemList",
"itemListElement":[
{{ $counter := 0 }}
{{ range where .Paginator.Pages "Params.hidden" "ne" true }}
{{ $counter = add $counter 1 }}
{
"@type":"ListItem",
"position": {{ $counter }},
"url": {{ .Permalink }}
} <!-- blank if singe, comma if more than one, blank if last -->
{{ end }}
]
}
</script>
{{ $s := slice
(dict "a" "wibble" "b" "wobble")
(dict "a" "wibble" "b" "wubble")
(dict "a" "foo" "b" "baz")
}}
{{ range $k, $_ := where $s "a" "wibble" }}
{{ if $k }}
,
{{ end }}
{{ .b }}
{{ end }}
--> wobble , wubble
idarek
August 17, 2022, 6:40pm
5
I am sorry, but I don’t know how to implement that into the above range.
diff --git a/layouts/_default/home.html b/layouts/_default/home.html
index a59a27e8b..0c327f4a6 100644
--- a/layouts/_default/home.html
+++ b/layouts/_default/home.html
@@ -16,14 +16,15 @@ <h1>{{ .Title }}</h1>
"@context":"https://schema.org",
"@type":"ItemList",
"itemListElement":[
- {{ $counter := 0 }}
- {{ range where .Paginator.Pages "Params.hidden" "ne" true }}
-{{ $counter = add $counter 1 }}
+ {{ range $k, $_ := where .Paginator.Pages "Params.hidden" "ne" true }}
+ {{ if $k }}
+ ,
+ {{ end }}
{
"@type":"ListItem",
- "position": {{ $counter }},
+ "position": {{ add $k 1 }},
"url": {{ .Permalink }}
- } <!-- blank if singe, comma if more than one, blank if last -->
+ }
{{ end }}
]
}
2 Likes
idarek
August 17, 2022, 7:03pm
7
Wow, that’s great. Thank you.
BTW, it’s a nice looking way to present a difference with -
and +
. Haven’t seen that before.
system
Closed
August 19, 2022, 7:05pm
9
This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.