DEV Community

Alex Spinov
Alex Spinov

Posted on

Templ Has a Free API That Builds Type-Safe HTML Templates in Go

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
Enter fullscreen mode Exit fullscreen mode

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>
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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)