简体   繁体   中英

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.

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

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 . 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 "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 :

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>
...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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