Templ generates Go code from HTML templates. Type-safe, fast, with LSP support in your editor. No more text/template runtime errors.
Quick Start
go install github.com/a-h/templ/cmd/templ@latest
Define a Template
// hello.templ
package main
templ Hello(name string) {
<div>
<h1>Hello, { name }!</h1>
<p>Welcome to Templ.</p>
</div>
}
templ Page(title string, body templ.Component) {
<!DOCTYPE html>
<html>
<head><title>{ title }</title></head>
<body>
@body
</body>
</html>
}
Use in Go
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
component := Page("Home", Hello("World"))
component.Render(r.Context(), w)
})
http.ListenAndServe(":3000", nil)
}
Type Safety
// This won't compile — wrong type
templ UserCard(user User) {
<div>{ user.Name }</div>
<div>{ user.Age }</div> // compile error if Age is int, not string
}
Templ vs text/template vs html/template
| Feature | Templ | text/template | html/template |
|---|---|---|---|
| Type-safe | Yes | No | No |
| LSP | Yes | No | No |
| Runtime errors | None | Common | Common |
| XSS protection | Automatic | No | Yes |
The Bottom Line
Templ is the right way to do HTML in Go. Type-safe, fast, with editor support. Stop using text/template for HTML.
Need to automate data collection or build custom scrapers? Check out my Apify actors for ready-made tools, or email spinov001@gmail.com for custom solutions.
Top comments (0)