How can I use division in a golang template?

huangapple go评论77阅读模式
英文:

How can I use division in a golang template?

问题

你可以在Go语言模板中使用除法运算符来实现除法操作。你可以通过将Id除以2来实现。以下是一个示例:

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

在这个示例中,div是一个自定义函数,用于执行除法运算。它接受两个参数,第一个参数是被除数,第二个参数是除数。如果除法运算的结果为真(非零),则输出"HEY, I CAN DO IT!",否则输出"WHY???"。

英文:

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

得分: 17

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}}`

	// 创建一个模板,添加函数映射,并解析文本。
	tmpl, err := template.New("foo").Funcs(fm).Parse(tmplTxt)
	if err != nil {
		panic(err)
	}

	// 运行模板以验证输出。
	err = tmpl.Execute(os.Stdout, 10)
	if err != nil {
		panic(err)
	}
}

输出:

5

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

英文:

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

huangapple
  • 本文由 发表于 2015年4月14日 19:50:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/29626542.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定