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:


You can read more about using a funcmap towards the end of this article -

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 (

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
  t.Execute(os.Stdout, nil)


On the Go Playground:


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.