2014-05-08 30 views
1

我想與一起調用模板的FuncMap如果是這樣的:調用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可能嗎?

+0

下面有兩種方法可以使用的很好的例子:http://stackoverflow.com/questions/23466497/how-to-truncate-a-string-in-a-golang-template – miltonb

回答

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

+0

謝謝!這正是我所需要的,儘管我調整了我的回報bool http://play.golang.org/p/jpsXdtZfB3 – jwesonga

0

聽起來像是你應該定義模板,它接受所需的數據,並返回一個INT /布爾所以模板可以保留作爲possibleL 簡單的邏輯之外的自己的函數這將是像這樣在您的Go代碼:

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

在您的模板:

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