繁体   English   中英

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

[英]How can I use division in a golang template?

如何在golang模板中使用除法。 我需要将Id除以2。

例如

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

text/template (以及随后的html/template )可以通过使用Template.Funcs将除法定义为函数来提供功能:

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

在您的情况下,具有除法函数的FuncMap可能如下所示:

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

完整的例子(但没有我试图了解你的意思, 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)
    }
}

输出:

游乐场: http //play.golang.org/p/VOhTYbdj6P

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM