Easy way to render HTML in Go

In this article I’ll show you how to render nested HTML template easily in Golang

For this tutorial, I’ll use renderer package to render our HTML template. Lets create a directory tutorial` in your $GOPATH/src . Use go get to install the above-mentioned package.

$ go get github.com/thedevsaddam/renderer/...

Our directory structure will look like:

Our directory structure

Create header.html, navbar.html and footer.html inside tutorial/inc . We are using bootstrap CDN to look cool. We are defining header, navbar, footer template as reusable code.

tutorial/tpl/inc/header.html
tutorial/tpl/inc/navbar.html
tutorial/tpl/inc/footer.html

Now we have our reusable template files, let’s create two templates, one for home and another for about page. Put these file inside tutorial/tpl directory.

tutorial/tpl/home.html
tutorial/tpl/about.html

Now all of our template files are ready, let’s create a main.go file inside the tutorial directory and write the code below:

tutorial/main.go

At line10 in main.go file we declared a rnd variable and inside init function, we assigned the variable using renderer package. In this case, we used ParseGlobPattern option to parse any .html file inside the tpl directory. Inside main function we declared two routes for home and about page. Inside home and about handlerFunc we used HTML method from render package and passed the template name in the third param.

We are ready….. :D , run the app using go run main.go and go to localhost:9000 in your web browser.

If you have any problem to understand any part of the article, or have any feedback or found anything that misleading please let me know using the comment section below :)

If you like the article don’t forget to let me know, hit the appreciate button and share the article with others.

Note: I’ll try to update the article based on your feedback. Thank you
If you like my writings please follow me Saddam H.

Help me to write more articles like this one