Calling functions from within a html/template

The only way I found to call functions of my executable from within a html template, like in

<div>{{ .Value 1 }}</div>
<div>{{ .Counter 17 }}</div>

was to create a dummy variable of a dummy type, change the functions “Value” and “Counter” to be methods that have this dummy type as receiver, and use the dummy variable as object in the template.Execute call.

err = t.Execute(w, Dummy)

Is there a better way?

You can use a template.FuncMap and assiciate it with your template as shown here: https://golang.org/src/text/template/examplefunc_test.go

3 Likes

You can read more about using a funcmap towards the end of this article - https://www.calhoun.io/using-functions-inside-go-templates/

If you have any questions I’m happy to help out.

1 Like

@Modran If you want an example to go from, here is a super simple one:

package main

import (
  "fmt"
  "html/template"
  "os"
)

func main() {
  const templString = "{{ myFunction 123 }}"
  t := template.Must(template.New("demo").Funcs(template.FuncMap{
    "myFunction": func(i int) (string, error) {
      return fmt.Sprintf("My function received: %d", i), nil
    },
  }).Parse(templString))
  t.Execute(os.Stdout, nil)

}

On the Go Playground: https://play.golang.org/p/0zRd-2glbv

2 Likes

Thank you!
My first thought was that the funcmap would add some overhead.
But now my question is obsolete, because I found a need for the “dummy”: it now stores the starting time of the httpHandler.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.