dscs63759
2018-06-26 17:50 阅读 135
已采纳

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

I tried to do this test to figure out how to make conditions like this:

<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>

I got this error "unexpected "%" in operand".

Any suggestions to solve this?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    duanpo8329 duanpo8329 2018-06-27 02:32

    You can't use operators like +, -, *, /, or % in templates, unfortunately. Instead you have to write custom functions and use a funcMap to bring them into your template.

    Here's an example on the Go Playground that detects even integers applied to a slightly modified version of your template text.

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

    点赞 评论 复制链接分享

相关推荐