douweng3383 2015-04-14 03:50
浏览 759
已采纳

如何在golang模板中使用除法?

How can I use division in a golang template. I need to divide Id by 2.

For example

{{if .Id/2}}
HEY, I CAN DO IT!
{{else}}
WHY???
{{end}}
  • 写回答

1条回答 默认 最新

  • dshakcsq64956 2015-04-14 04:09
    关注

    The package text/template (and subsequently html/template) can provide the functionality by defining division as a function using Template.Funcs:

    func (t *Template) Funcs(funcMap FuncMap) *Template
    

    In your case, a FuncMap with a divide function could look something like this:

    fm := template.FuncMap{"divide": func(a, b int) int {
        return a / b
    }}
    

    Full example (but without me trying to understand what you mean with if a/2):

    package main
    
    import (
        "os"
        "text/template"
    )
    
    func main() {
        fm := template.FuncMap{"divide": func(a, b int) int {
            return a / b
        }}
    
        tmplTxt := `{{divide . 2}}`
    
        // Create a template, add the function map, and parse the text.
        tmpl, err := template.New("foo").Funcs(fm).Parse(tmplTxt)
        if err != nil {
            panic(err)
        }
    
        // Run the template to verify the output.
        err = tmpl.Execute(os.Stdout, 10)
        if err != nil {
            panic(err)
        }
    }
    

    Output:

    5

    Playground: http://play.golang.org/p/VOhTYbdj6P

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部