如何在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
带有除法功能的a可能看起来像这样:
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)
}
}
输出:
5
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句