调用 FuncMap 和条件函数

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

Calling FuncMap and condition function

问题

我想在模板中与if一起调用FuncMap,类似于:

{{if lt myFunc .templateVariable condition}} <span class="foo"> {{.templateVar}}</span> {{else}} {{.templateVar}} {{end}}

查看文档,只显示了这个:

{{if eq .A 1 2 3 }} equal {{else}} not equal {{end}}

在Go中是否可能实现这个?

英文:

I want to call a FuncMap in a template together with an if, something like:

{{if lt myFunc .templateVariable condition}} <span class="foo"> {{.templateVar}}</span> {{else}} {{.templateVar}} {{end}}

Looking at the docs it shows this only:

{{if eq .A 1 2 3 }} equal {{else}} not equal {{end}}

Is this possible in Go?

答案1

得分: 3

你是不是在寻找这样的内容?

func main() {

    funcMap := template.FuncMap{
        "calculate": func(i int) int { return 42 },
    }

    tmpl := `{{$check := eq (calculate 1) 42}}{{if $check}}正确答案{{end}}{{if not $check}}错误答案{{end}}`

    t, _ := template.New("template").Funcs(funcMap).Parse(tmpl)
    t.Execute(os.Stdout, "x")

}

点击这里 运行代码。

英文:

Are you looking for something like this?

func main() {

	funcMap := template.FuncMap{
		"calculate": func(i int) int { return 42 },
	}

	tmpl := `{{$check := eq (calculate 1) 42}}{{if $check}}Correct answer{{end}}{{if not $check}}Wrong answer{{end}}`

	t, _ := template.New("template").Funcs(funcMap).Parse(tmpl)
	t.Execute(os.Stdout, "x")

}

Play

答案2

得分: 0

听起来你应该在模板之外定义自己的函数,该函数接受所需的数据并返回一个整数/布尔值,这样在模板中可以保持逻辑尽可能简单。在你的Go代码中,可以这样写:

func (p *templateData) myFunc(templateVar Type, condition Type) int {
    // 逻辑处理
    return 0
}

在你的模板中:

{{if lt myFunc .templateVariable }} ...

请注意,这只是一个示例,你需要根据实际情况进行适当的修改。

英文:

Sounds like you should define your own function outside of the template, which accepts the required data and returns a int/bool so in the template you can keep the logic as simple as possibleL
It would be something like this in your Go code:

 func (p *templateData) myFunc(templateVar Type, condition Type)  int {
     // logic
     return 0
 }

Within your template:

 {{if lt myFunc .templateVariable }} ...

huangapple
  • 本文由 发表于 2014年5月9日 03:36:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/23550967.html
匿名

发表评论

匿名网友

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

确定