DEV Community

Cover image for How to call a function from within a Go html template
Go4WebDev
Go4WebDev

Posted on • Edited on

How to call a function from within a Go html template

#go

Using Go for web development is not that common, but I find it rather simple to create static web sites and the site often will be faster than other tools like Drupal, Wordpress and PHP.

Web development using Go means that you use at least 3 other “languages”. HTML, CSS and Javascript. The challenge is to get these languages to “talk” to each other. It is rather trivial to put data in a Go html template, but sometimes you want the HTML template to call a function in Go.

This is of course possible, but all sources I have found do not explain this in a simple way. The Go documentation is not that friendly to a newbie. And almost all examples on the net are either at “hello world” level OR too complicated.

Finally I found a solution by using 3 simple steps. Hope this will help somebody that also has been struggling with this.

  1. Write the HTML and call the function with parameters.
  2. Tell the templates to use this function.
  3. Finally create the desired func in Go.

Using Funcs in HTML you can do a lot of things in a HTML template.

Here is the code and live preview https://funcs.go4webdev.org

Top comments (0)