Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

proposal: write up how to use with https://github.com/gin-gonic/gin #50

Closed
a-h opened this issue Jun 5, 2022 · 3 comments · Fixed by #203
Closed

proposal: write up how to use with https://github.com/gin-gonic/gin #50

a-h opened this issue Jun 5, 2022 · 3 comments · Fixed by #203
Labels
documentation Improvements or additions to documentation good first issue Good for newcomers hacktoberfest Good issue for hacktoberfest.

Comments

@a-h
Copy link
Owner

a-h commented Jun 5, 2022

No description provided.

@cayter
Copy link

cayter commented Jun 28, 2023

Trying to get this working with Gin but am facing challenges. Any update on this? Thanks.

@cayter
Copy link

cayter commented Jun 28, 2023

Got it working.

renderer/templ.go

package renderer

import (
	"context"
	"net/http"

	"github.com/a-h/templ"
	"github.com/gin-gonic/gin/render"
)

type TemplRender struct {
	Code int
	Data templ.Component
}

func (t TemplRender) Render(w http.ResponseWriter) error {
	w.WriteHeader(t.Code)
	if t.Data != nil {
		return t.Data.Render(context.Background(), w)
	}

	return nil
}

func (t TemplRender) WriteContentType(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
}

func (t *TemplRender) Instance(name string, data interface{}) render.Render {
	if templData, ok := data.(templ.Component); ok {
		return &TemplRender{
			Code: http.StatusOK,
			Data: templData,
		}
	}
	return nil
}

main.go

package main

import (
  "<module>/renderer"
)

func main() {
  r := gin.Default()
  r.HTMLRender = &renderer.TemplRender{}
  
  r.GET("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "", page.Home())
  })
}

@a-h a-h added documentation Improvements or additions to documentation good first issue Good for newcomers hacktoberfest Good issue for hacktoberfest. labels Sep 30, 2023
@a-h
Copy link
Owner Author

a-h commented Sep 30, 2023

If this became an example in the examples directory, and made its way into the docs, that would be great! Good Hacktoberfest PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation good first issue Good for newcomers hacktoberfest Good issue for hacktoberfest.
Projects
None yet
2 participants