去:在模板里面可以使用模数吗? [英] Go: Is there a modulus I can use inside a template

查看:94
本文介绍了去:在模板里面可以使用模数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题正如标题中所述。我正在尝试这样做:

  {{range $ index,$ element:= .Products}} 
{{if $ index%4 == 0}}< div class =row> {{end}}
< div class =columns small-3 product>
< img src =/ img / {{。ImageUrl}}alt ={{。ImageUrl}}/>
< a href =/ product>
< h3> {{。标题}}< / h3>
< / a>
< p>
{{.Description}}
< / p>
< p>
{{。价格}} /升
< / p>
< / div>
{{if index%4 == 0}}< / div> {{end}}
{{end}}

我得到这个错误:

template:products.html:9:unexpected in operand



是否有另一种方法可以在模板中进行模数计算?

解决方案

使用逻辑添加模板功能你需要。例如:

  t:= template.New()
t.Funcs(template.FuncMap { mod':func(i,j int)bool {return i%j == 0}})
t.Parse(`... {{if mod $ index 4}}< div class =row > {{{end}} ...`)

游乐场例子


My question is as stated in the title. I am trying to do something like:

{{range $index, $element := .Products}}
    {{if $index % 4 == 0}}<div class="row">{{end}}
        <div class="columns small-3 product">
            <img src="/img/{{.ImageUrl}}" alt="{{.ImageUrl}}" />
                <a href="/product">
                    <h3>{{.Title}}</h3>
                </a>
                <p>
                  {{.Description}}
                </p>
                <p>
                    {{.Price}} / liter
                </p>
                </div>
        {{if index % 4 == 0}}</div>{{end}}
{{end}}

I get the error:

template: products.html:9: unexpected "%" in operand

Is there an alternate way to do modulus in a template?

解决方案

Add a template function with the logic you need. For example:

t := template.New("")
t.Funcs(template.FuncMap{"mod": func(i, j int) bool { return i%j == 0 }})
t.Parse(`... {{if mod $index 4}}<div class="row">{{{end}} ...`)

playground example

这篇关于去:在模板里面可以使用模数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆