简体   繁体   English

如何打印函数的返回值?

[英]How do I print return value of a function?

Here is my function definition which returns a string 这是我的函数定义,它返回一个字符串

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

I'm trying to print it like this: 我正在尝试像这样打印它:

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

http response is getting terminated when I'm trying to print. 当我尝试打印时,http响应将终止。

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 返回一个布尔值,然后使用if仍然有效,我仍然很好奇如何打印从函数返回的字符串

The problem you have is that "home" and .Context will be the 3:rd and 4:th argument of printf and not the arguments of addClassIfActive . 您遇到的问题是"home".Context将是printf的3:rd和4:th参数,而不是addClassIfActive The return value of addClassIfActive becomes the 2:nd argument for printf . addClassIfActive的返回值成为printf的2:nd参数。

But the solution is simple: you don't have to use printf to print. 但是解决方案很简单: 您不必使用printf进行打印。

If your function just returns a string, you can simply print it by writing: 如果您的函数仅返回一个字符串,则可以简单地通过编写以下命令来打印它:

{{addClassIfActive "home" .Context}}

Full working example: 完整的工作示例:

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)
    }

}

Output: 输出:

home content 家庭内容

Playground 操场

You can't call functions in templates. 您不能在模板中调用函数。

What you can do is use FuncMaps : 可以使用FuncMaps进行操作

templates.go templates.go

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

your_template.tmpl your_template.tmpl

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

I haven't tested this exact syntax, but I am using FuncMaps elsewhere. 我没有测试过这种确切的语法,但是我在其他地方使用FuncMaps。 Make sure to read the better docs at text/template on FuncMaps for more examples. 请确保阅读有关FuncMaps 上text / template更好文档,以获取更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM