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)) }
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.
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> }
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.
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/.
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.
The above is the detailed content of Integrating Templ. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

This article introduces a variety of methods and tools to monitor PostgreSQL databases under the Debian system, helping you to fully grasp database performance monitoring. 1. Use PostgreSQL to build-in monitoring view PostgreSQL itself provides multiple views for monitoring database activities: pg_stat_activity: displays database activities in real time, including connections, queries, transactions and other information. pg_stat_replication: Monitors replication status, especially suitable for stream replication clusters. pg_stat_database: Provides database statistics, such as database size, transaction commit/rollback times and other key indicators. 2. Use log analysis tool pgBadg
