I really try to find samples in the discourse before posting. This is a Hugo and bootstrap together question.
I have a collection of Events that I am Ranging over. I want to list items on a page like this:
1 2
3 4
5 6
What I understand of bootstrap is that I need to add a <div class="row">
every two items from my Range. Or…
1 2 3
4 5 6
Would require one every three items.
The number of items does not matter, what I am trying to figure out is how to conditionally add the row break inside the range in a template. Is this supported? Should I be using a Paginator or GroupBy?
bep
October 19, 2018, 5:16pm
2
You can do this with a regular indexed range using the modBool
(or mod
) template func. Something ala
{{ if not .page.Parent.IsHome }}
<div class="browsesection">
<div class="docstitle">
<h3><a href="{{ .page.RelPermalink }}">{{ .page.Params.bigheader | default .page.Title }}</a></h3>
</div>
{{ if ge (len $pages) 1 }}
<div class="pages">
{{ $num_pages := len $pages }}
{{ if gt $num_pages 0 }}
{{ $column_size := (div $num_pages 3.0) | math.Ceil | int | default 1 }}
{{ range $i, $e := $pages.ByWeight }}
{{ $offset := mod $i $column_size | add 1 }}
{{ if eq $offset 1 }}
<div class="browsecolumn">
{{ end }}
{{ $isForeignLanguage := (ne .Lang $.ctx.Lang)}}
<a href="{{ .RelPermalink }}"{{ if $isForeignLanguage }} target="_blank" {{ end }}>{{ printf "%02d - %s" (add $i 1) .LinkTitle }}{{ if $isForeignLanguage }} <small>({{ .Lang | upper }})</small>{{ end }}</a><br>
{{ if or (eq $offset $column_size) (eq (add $i 1) $num_pages)}}
</div>
{{ end }}
{{ end }}
OK, I found this:
Hugo provides a modulo template func:
{{ range $k, $v := first 410 (.Data.Pages.ByDate.Reverse) }}
{{ if mod $k 3 | eq 0 }}
{{ end }}
{{ end }}
Now my code is:
{{ $pages := where .Data.Pages "Section" "event" }}
{{ $pages_count := len $pages }}
{{ if ge $pages_count 1 }}
{ range $i, $sorted := $pages.ByParam "start" }}
<div class="event-card__title"><a href="{{ .URL }}" title="{{ .Title }}">{{ .Title }}</a></div>
{{ if modBool $i 3 }}
</div> <!-- end row -->
<div class="row">
{{ end }}
{{ end }}
But it is adding a row after the first and then every 3 after that.
1
2 3 4
5 6
bep
October 19, 2018, 5:25pm
4
MatthewMcD:
{{ if modBool $i 3 }}
$i starts at 0 and modBool 0 3
is true. I’m a bit tired after a long day, but I suspect modBool (add $i 1) 3
should work.
Thanks Bep. That fixed it.