Home > Article > Backend Development > 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?
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.
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)) }
It looks more complicated than it really is. Lets look at this a step at a time.
port := ":3000"
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())
home is an instance of the Home function from home.templ.
http.Handle("/", templ.Handler(home))
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 }
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"))))
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))
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.
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> }
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") }
Passing "Home" into @Layout(title string) sets the pages title to, you guessed it, Home.
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/.
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.
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.
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.
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.
The above is the detailed content of Integrating Templ. For more information, please follow other related articles on the PHP Chinese website!