在行之间交替设计的Go模板

huangapple go评论63阅读模式
英文:

go template alternating design between rows

问题

我有一个简单的模板,用于获取博客文章列表:

<div class="row">
    <div class="cell">
        {{range .Pages}}

        <p class="dialogue dialogue--wide">
            <a href="{{.Slug}}">{{.Title}} </a>
        </p>

        {{end}}
        <br />
        <br />
        <br />
    </div>
</div>

我想在文章之间交替设计,例如,第一个文章使用特定的

类,如

而第二个记录(或者你喜欢的偶数和奇数记录)使用另一个

,例如

谢谢!

英文:

I have a simple template fetching a list of blog posts:

&lt;div class=&quot;row&quot;&gt;
    &lt;div class=&quot;cell&quot;&gt;
        {{range .Pages}}

        &lt;p class=&quot;dialogue dialogue--wide&quot;&gt;
            &lt;a href=&quot;{{.Slug}}&quot;&gt;{{.Title}} &lt;/a&gt;
        &lt;/p&gt;

        {{end}}
        &lt;br /&gt;
        &lt;br /&gt;
        &lt;br /&gt;
    &lt;/div&gt;
&lt;/div&gt;

I would like to alternate the design between posts e.g. the first will use a certain <p> class like
<p class="dialogue dialogue--wide">
and the second record (or even and odd records if you prefer) another p e.g.
<p class="dialogue dialogue--narrow">

thank you!

答案1

得分: 4

我建议使用CSS来解决这个问题,以节省一些麻烦。你可以在nth-child中使用oddeven

.dalogue:nth-child(odd) {
    // CSS属性
}

另外,你也可以使用项目的索引。下面的代码中,我使用取模运算符来判断是奇数还是偶数。

{{ range $index, $page := .Pages }}
 {{ if eq (mod $index 2) 0 }} odd {{ else }} even {{ end }}
{{end}}

请注意,我在奇数和偶数之间进行了切换。因为索引从0开始而不是从1开始。但是在查看表格时,你是从1开始计数的,这也是CSS的行为方式。

我使用template.Funcs自己实现了mod函数。

t.Funcs(map[string]any{"mod": func(a, b int) int { return a % b }})
英文:

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{&quot;mod&quot;: func(a, b int) int { return a % b }})

https://go.dev/play/p/aAupH-4CugV

huangapple
  • 本文由 发表于 2022年4月14日 04:06:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/71863296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定