dscs63759 2018-06-26 17:50
浏览 195
已采纳

如何在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 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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据