I have a simple template fetching a list of blog posts:
<div >
<div >
{{range .Pages}}
<p >
<a href="{{.Slug}}">{{.Title}} </a>
</p>
{{end}}
<br />
<br />
<br />
</div>
</div>
I would like to alternate the design between posts e.g. the first will use a certain
class like
and the second record (or even and odd records if you prefer) another p e.g.thank you!
CodePudding user response:
I suggest solving this with CSS to save yourself some trouble. You can use odd
or even
in nth-child
:
.dalogue:nth-child(odd) {
// CSS Property
}
Alternatively, you can use the index of the items. Below, I am using the modulo operator to determine if it's odd or even.
{{ range $index, $page := .Pages }}
{{ if eq (mod $index 2) 0 }} odd {{ else }} even {{ end }}
{{end}}
Note, I am switching odd and even around. Because the index starts at 0 and not at 1. But when looking at a table, you start counting at 1 and this is also how CSS would behave.
I have implemented the mod function myself using template.Funcs.
t.Funcs(map[string]any{"mod": func(a, b int) int { return a % b }})