如何在 golang 模板中的 LOOP 内执行 IF/ELSE 条件?

How to do IF/ELSE conditions inside LOOP in golang templates?

我试图做这个测试来弄清楚如何创造这样的条件:

<h1>Country Index</h1>

<style>
.odd{
    background: orange;
    color: black;
    font-size: 1.5em;
}
.even{
    background: rgb(0, 121, 235);
    color: white;
    font-size: 1.5em;
}
</style>

<ul>
    {{ range $index, $item := .Tee }}
        {{ if $index % 2 == 0 }}
            <li class="even">{{ $index }} - {{ $item }}</li>
        {{ else }}
            <li class="odd">{{ $index }} - {{ $item }}</li>
        {{ end }}
    {{ end }}
</ul>

我收到此错误“操作数 中出现意外的“%”。

有什么解决这个问题的建议吗?

很遗憾,您不能在模板中使用 +、-、*、/ 或 % 等运算符。相反,您必须编写自定义函数并使用 funcMap 将它们引入模板。

这是 Go Playground 上的一个示例,它检测应用于模板文本的稍微修改版本的偶数。

https://play.golang.org/p/LWEhE_TI31o

您可以创建 bool 辅助变量并在每次迭代时更改其状态。

{{$odd := true}}
{{range $data := .Tee}}
   {{if $odd}}
      <p>action for odd.</p>
   {{else}}
      <p>action for not odd.</p>
   {{end}}
{{$odd = not $odd}}
{{end}}