Learning Golang - templates
When I started learning about Golang templates much of what I read was around their syntax and feature set. It didn’t take long, but I found myself struggling to do things that struck me as being pretty basic. So I figured I’d write down a few things I’ve learned.
By no means is this intended to be a proper (or even correct) howto on Golang templates, rather it’s just what I’ve learned so far. Here’s what I was trying to accomplish:
- Have a directory of templates (
- Have a directory of static files (css, images, etc).
- Use some templates as full pages (
- Use some templates as partials (
- Serve static content in a manner similar to http.FileServer.
- Exclude templates from the static files being served.
- Support custom template functions.
- Compile everything into a single static binary (including templates and static files).
What I used
Here’s a quick punch list of the things I used and what they are for.
go get github.com/jteeuwen/go-bindata/... go get github.com/elazarl/go-bindata-assetfs/... go get github.com/julienschmidt/httprouter
The goal was to wind up with something like this:
. ├── functions.go ├── main.go ├── templates │ ├── footer.html │ ├── header.html │ └── hello.html └── static └── golang.png
static folder I’d put static assets, things like pictures,
templates, and template functions would go inside
application itself would then be
A hello world example might look like this, with a single function to uppercase something:
Sample hello world application
Build the application
go generate go build && ./golang-templates-example
Then you can use something to test it:
go-bindata does a great job
of compiling static assets into a single binary, and
makes it easy to serve those assets over http. I wasn’t able to find
an easy way to expose
ExecuteTemplate in a manner that made it
possible to add a function map, but a quick for loop in
to do the trick. Partials are managed here purely using upstream
documentation. I have not yet sorted out how to exclude the templates
from being served over http (hence the strike through). A working
example if this sample project is on Github:
For those of you that actually know how to do this stuff, I’d love to hear from you (via pull request or whatever).
- Switched from
html/template, thanks strothjs.
- Removed templates from static content served, GH2.