Integrating Templ

This is going to be a longer one as we need three (3) files now. Also, we need a static directory for files like favicon.ico, a css file (if you choose to use css), logo, or any other static file.

net/http docs. These are your best friend.

Let’s begin, shall we?

Install and Set Up

Thankfully, the way Go is set up, this is a straight forward process.
go install github.com/a-h/templ/cmd/templ@latest
The above command gets you the templ binary (you did set your PATH, right?).
go get github.com/a-h/templ
This one loads templ into your go.mod.

That’s it. Install and set up are done.

And the struggle

The most difficult part of this process, was getting styles.css to load properly. If you are not using a css file, you can skip the line regarding the static directory.

// File: /root/cmd/server/main.go
package main import ( [go mod module name]/internal/views
)
func main(){ port := ":3000" home := templ.Component(views.Home()) http.Handle("/", templ.Handler(home)) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) log.Fatal(http.ListenAndServe(port, nil))
}
Enter fullscreen mode
Exit fullscreen mode

It looks more complicated than it really is. Lets look at this a step at a time.

port := ":3000"
Enter fullscreen mode
Exit fullscreen mode

port is, well, the port (I’m presuming you know what a port is). When passing the port to http.ListenAndServe(addr string, handler Handler), make sure you include :, else it will not go run or go build.

home := templ.Component(views.Home())
Enter fullscreen mode
Exit fullscreen mode

home is an instance of the Home function from home.templ.

http.Handle("/", templ.Handler(home))
Enter fullscreen mode
Exit fullscreen mode

All we are doing here, is passing home to templ‘s Handler(), which does the same thing http.Handler() does, only a little more specific. Here is the source to templ.Handler():

type Handler struct { h slog.Handler m *sync.Mutex w io.Writer
}
Enter fullscreen mode
Exit fullscreen mode

This Handler is assigned to the root dir pattern and then used by ServeMux, the http multiplexer. A fancy way of saying it handles all the paths for a given Top Level Domain.

http.Handle("/static", http.StripPrefix("/static", http.FileServer(http.Dir("./static"))))
Enter fullscreen mode
Exit fullscreen mode

This is a long one but can easily be digested. http.Handle(pattern string, handler Handler) we went over, above. The pattern, in this case, is the static directory. The Handler is made of Higher-Order Functions. That simply means that functions are treated as data, as well, and can be assigned to variables and/or passed as a parameter.

In this case, we’re passing http.Dir("./static"). http.Dir(dir string) is used to implement a native FileSystem (opens the dir), and is limited to the $pwd/$cwd. That is why we pass ".". We’re starting from the root. This is passed into http.FileServer(root FileSystem) Handler which returns the needed Handler. Then we pass that into http.StripPrefix(pattern string, fs FileSystem) which does exactly what it sounds like, removes the directory name from the path. The real benefit, when you think about what it’s doing, /static is now /, which is root. So where does the css apply? On the home page.

That wasn’t so bad, was it?

log.Fatal(http.ListenAndServe(port, nil))
Enter fullscreen mode
Exit fullscreen mode

http.ListenAndServe(addr string, handler Handler) error is the last part. This function also returns non-nil error values, so error handling is STRONGLY advised. log.Fatal(v ...any) takes any type and is "equivalent to calling Print() on os.Exit(1)"source. Meaning, if the program exits with any other value than 0 (i.e. crash), it will log the event.

At some point, I’m going to look into http.ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error. Right now, TLS is being served by my host (not self-hosted).

And with that, main.go is done for now.

Templ templates

Our first template, will be ./internal/views/layout.templ. This file will handle the way the page is displayed. If you’re coming from React or Nextjs, it’s your page.tsx file.

// File: /root/internal/views/layout.templ
package views templ Layout( title string ){ <!DOCTYPE html> <html lang="en"> <head> <link rel="icon" type="image/x-icon" href="/static/favicon.ico"/> <link rel="stylesheet" type="text/css" href="/static/styles.css"/> <title>{title}</title> </head> <body> {children ...} </body> </html>
}
Enter fullscreen mode
Exit fullscreen mode

Really straight forward.

The next template is home.templ. This will contain the contents of /.

// File: /root/internal/views/home.templ
package views templ Home(){ @Layout("Home")
}
Enter fullscreen mode
Exit fullscreen mode

Passing "Home" into @Layout(title string) sets the pages title to, you guessed it, Home.

Wrapping it up

Okay, like I said in the beginning, it’s a lot this time. Two (2) more things and we’re finished with implementing and testing templ.

# 1 - make sure `go.sum` is up-to-date
go mod tidy
# 2 - have templ generate go files
templ generate
# 3a - build it out
go build ./cmd/server/main.go
./main
# 3b - or test it out
go run ./cmd/server/main.go
# you can shorten the path to
go run ./cmd/server/.
Enter fullscreen mode
Exit fullscreen mode

You should see your go/templ web page in all of its glory; even if it’s burning your retinas because you forgot to change the background color in your css.

Addendum

You can pass contents templ.Component as a parameter if you choose to use jsx tags as templ templates. Likewise, templ also provides a css components for custom templates.

Errata

If you spot an error, are having any troubles, or I missed something, please, feel free to leave a comment and I’ll do my best to update and/or help.

Up Next

Since our web sites are going to change (adding content), we’re going to go through the steps to set up a GitHub-Hosted Runner to handle building out the files and commit-ting them so we can deploy it.

I will be adding a git repo for this project, in the future. It will have all of the files we’re writing and a .github/go.yml file for GitHub Actions.

Buy Me A Coffee


Discover more from Coursity

Subscribe to get the latest posts sent to your email.

Leave a Comment

Your email address will not be published. Required fields are marked *

Discover more from Coursity

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top