templ is a great view framework but there is no clear documentation (as of writing) showing how to use it with the Echo web framework. This short guide should show you how to set it up:
Install templ and echo:
go get github.com/a-h/templ
go get github.com/labstack/echo/v4
Create a templ view file and layout (or whatever you want):
// views/layout.templ
package views
templ Layout(title string) {
<html>
<head>
<title>{ title }</title>
</head>
<body>
{ children... }
</body>
</html>
}
}
// views/home.templ
package views
templ Home(title string) {
@Layout(title) {
<h1>Welcome home!</h1>
}
}
In your main.go
(or whever you create your Echo server), create a server and a route handler:
package main
func main {
e := echo.New()
e.GET("/", homeHandler)
e.Logger.Fatal(e.Start(":3000")
}
func homeHandler(c echo.Context) error {
return render(c, views.Home("Page Title"))
}
func render(ctx echo.Context, cmp templ.Component) error {
return cmp.Render(ctx.Request().Context(), ctx.Response())
}
The key piece here is the render
function which adheres to the interface Echo expects for returning a response.
Add some commands to a Makefile (or any other tooling you use) to build templ templates into go files. Combine this with any other build/dev steps you need for your project:
.PHONY: dev build
dev:
@templ generate --watch
build:
@templ generate
.DEFAULT_GOAL := dev
Now run make
or make dev
to watch for template changes or make build
to build.
That's it (I think 😅), lemme know if you have any questions/comments/suggestions!
Can you also describe or write a folder structure best suited for this stack. new to go so i am not sure where to put what. Trying to use this framework with htmx and tailwind too.