Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save danawoodman/7f93b7c149deec4187679e74d7ff570e to your computer and use it in GitHub Desktop.
Save danawoodman/7f93b7c149deec4187679e74d7ff570e to your computer and use it in GitHub Desktop.
Using Golang templ with the Echo framework

Using Golang templ with the Echo framework

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 dependencies

Install templ and echo:

go get github.com/a-h/templ
go get github.com/labstack/echo/v4

Create views

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>
  }
}

Create server

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.

Setup Makefile

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.

Conclusion

That's it (I think 😅), lemme know if you have any questions/comments/suggestions!

@mvolkmann
Copy link

How should views be declared in main.go?

@danawoodman
Copy link
Author

i didn't show it but you just import the views in main.go since they're regular go files after you run templ generate

@hackertron
Copy link

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.

@danawoodman
Copy link
Author

here is just one possible structure:

cmd/
  server/
    main.go <- initialize server command 
internal/
  views/
    public/
      htmx.js
    home.templ
    layout.templ
  handlers/
    home.go
  models/
    user.go <- backend agnostic user model
  data/
    user.go <- user data storage (e.g. postgres db access)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment