Pergunta

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?

Foi útil?

Solução

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

Outras dicas

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 }} ...
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top