调用FuncMap和条件函数

时间:2014-05-08 19:36:08

标签: go

我想在模板中调用FuncMap以及if,如:

{{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吗?

2 个答案:

答案 0 :(得分:3)

你在找这样的东西吗?

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

答案 1 :(得分:0)

听起来你应该在模板之外定义自己的函数,它接受所需的数据并返回一个int / bool,所以在模板中你可以保持逻辑尽可能简单L 你的Go代码就是这样的:

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

在您的模板中:

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