2014-01-29 130 views
1

這裏是我的函數的定義,它返回一個字符串如何打印函數的返回值?

"addClassIfActive": func(tab string, ctx *web.Context) string

我試圖打印這樣的:當我試圖

<a href="/home/"{{ printf "%s" addClassIfActive "home" .Context }}>Home</a>

HTTP響應遭到停權打印。

我在做什麼錯?

返回一個布爾值,然後使用作品如果,我還是很好奇如何打印字符串從函數

回答

4

你的問題是,"home".Context將是3:次和4:日的printf論證和addClassIfActive沒有參數。 addClassIfActive的返回值成爲printf的2:nd參數。

但是解決方法很簡單:您不必使用printf進行打印。

{{addClassIfActive "home" .Context}} 

全部工作示例:

package main 

import (
    "html/template" 
    "os" 
) 

type Context struct { 
    Active bool 
} 

var templateFuncs = template.FuncMap{ 
    "addClassIfActive": func(tab string, ctx *Context) string { 
     if ctx.Active { 
      return tab + " content" 
     } 

     // Return nothing 
     return "" 
    }, 
} 

var htmlTemplate = `{{addClassIfActive "home" .Context}}` 

func main() { 
    data := map[string]interface{}{ 
     "Context": &Context{true}, // Set to false will prevent addClassIfActive to print 
    } 

    // We create the template and register out template function 
    t := template.New("t").Funcs(templateFuncs) 
    t, err := t.Parse(htmlTemplate) 
    if err != nil { 
     panic(err) 
    } 

    err = t.Execute(os.Stdout, data) 
    if err != nil { 
     panic(err) 
    } 

} 

輸出:

如果你的函數只返回一個字符串,你可以簡單地寫打印內容

Playground

+0

我沒有嘗試,這是印刷zgotmplz,而不是什麼函數返回 –

+0

我的錯誤,這是不安全的HTML,http://stackoverflow.com/questions/14765395/why-am-i-seeing -zgotmplz-in-my-go-html-template-output –

+0

啊,是的。我從來沒有反映你試圖輸出字符串的位置。很高興你解決了它。 – ANisus

0

不能調用函數模板返回。

什麼你可以做的是使用FuncMaps

templates.go

var t = template.New("base") 
// ParseFiles or ParseGlob, etc. 
templateHelpers := template.FuncMap{ 
     "ifactive": AddClassIfActive, 
    } 
    t = t.Funcs(templateHelpers) 

your_template.tmpl

... 
<span class="stuff">{{ if eq .Context | ifactive }} thing {{ else }} another thing {{ end }}</span> 
... 

我沒有測試過這個確切的語法,但我正在使用FuncMaps elsew這裏。請確保閱讀FuncMaps上的better docs at text/template以獲取更多示例。