1

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Chakradar Raju
  • 2,691
  • 2
  • 26
  • 42

2 Answers2

4

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

ANisus
  • 74,460
  • 29
  • 162
  • 158
0

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.

elithrar
  • 23,364
  • 10
  • 85
  • 104