如何打印函数的返回值?

huangapple go评论162阅读模式
英文:

How do I print return value of a function?

问题

这是我的函数定义,它返回一个字符串:

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

我试图这样打印它:

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

当我尝试打印时,HTTP响应被终止。

我做错了什么?

返回一个布尔值,然后使用if语句可以工作,但我还是想知道如何打印函数返回的字符串。

英文:

Here is my function definition which returns a string

&quot;addClassIfActive&quot;: func(tab string, ctx *web.Context) string

I'm trying to print it like this:

&lt;a href=&quot;/home/&quot;{{ printf &quot;%s&quot; addClassIfActive &quot;home&quot; .Context }}&gt;Home&lt;/a&gt;

http response is getting terminated when I'm trying to print.

What am I doing wrong?

Returning a boolean, and then using if works, still I'm curious how to print string returned from a function

答案1

得分: 4

你遇到的问题是"home".Context将成为printf的第三个和第四个参数,而不是addClassIfActive的参数。addClassIfActive的返回值将成为printf的第二个参数。

但解决方法很简单:你不需要使用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 ""
	},
}

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

func main() {
	data := map[string]interface{}{
		"Context": &Context{true}, // 如果设置为false,将阻止addClassIfActive打印
	}

	// 创建模板并注册模板函数
	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)
	}

}

输出:

home content

Playground

英文:

The problem you have is that &quot;home&quot; and .Context will be the 3:rd and 4:th argument of printf and not the arguments of addClassIfActive. The return value of addClassIfActive becomes the 2:nd argument for printf.

But the solution is simple: you don't have to use printf to print.

If your function just returns a string, you can simply print it by writing:

{{addClassIfActive &quot;home&quot; .Context}}

Full working example:

package main

import (
	&quot;html/template&quot;
	&quot;os&quot;
)

type Context struct {
	Active bool
}

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

		// Return nothing
		return &quot;&quot;
	},
}

var htmlTemplate = `{{addClassIfActive &quot;home&quot; .Context}}`

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

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

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

}

Output:

>home content

Playground

答案2

得分: 0

你可以在模板中调用函数。

你可以使用FuncMaps来实现:

templates.go

var t = template.New("base")
// ParseFiles或ParseGlob等
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。请确保阅读text/template的更好文档以获取更多示例。

英文:

You can't call functions in templates.

What you can do is use FuncMaps:

templates.go

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

your_template.tmpl

...
&lt;span class=&quot;stuff&quot;&gt;{{ if eq .Context | ifactive }} thing {{ else }} another thing {{ end }}&lt;/span&gt;
...

I haven't tested this exact syntax, but I am using FuncMaps elsewhere. Make sure to read the better docs at text/template on FuncMaps for more examples.

huangapple
  • 本文由 发表于 2014年1月29日 14:52:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/21424085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定