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

ccl*_*zob 4 go

如何在golang模板中使用除法.我需要除以Id2.

例如

{{if .Id/2}}
HEY, I CAN DO IT!
{{else}}
WHY???
{{end}}
Run Code Online (Sandbox Code Playgroud)

ANi*_*sus 13

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

func (t *Template) Funcs(funcMap FuncMap) *Template
Run Code Online (Sandbox Code Playgroud)

在你的情况下,FuncMap具有除法函数的a看起来像这样:

fm := template.FuncMap{"divide": func(a, b int) int {
    return a / b
}}
Run Code Online (Sandbox Code Playgroud)

完整的例子(但没有我试图理解你的意思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)
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

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

  • ....我简直不敢相信这在 7 年后的 golang 模板中没有 +-*/ 函数 (4认同)