2014-01-29 127 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以获取更多示例。