/*
* Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
*
* This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
* more information.
*/
// Package renderer provides a gin HTMLRender implementation.
package renderer
import (
"context"
"net/http"
"github.com/a-h/templ"
"github.com/gin-gonic/gin/render"
)
// TemplRender is a gin HTMLRender implementation for templ rendering.
type TemplRender struct {
Ctx context.Context
Status int
Component templ.Component
}
// New constructs a new TemplRender struct.
func New(ctx context.Context, status int, component templ.Component) *TemplRender {
return &TemplRender{
Ctx: ctx,
Status: status,
Component: component,
}
}
// Instance returns a new TemplRender instance.
func (t *TemplRender) Instance( /* name */ _ string, component interface{}) render.Render {
if templComponent, ok := component.(templ.Component); ok {
return &TemplRender{
Ctx: context.Background(),
Status: -1,
Component: templComponent,
}
}
return nil
}
// Render executes a template and writes its result.
func (t TemplRender) Render(w http.ResponseWriter) error {
t.WriteContentType(w)
if t.Status != -1 {
w.WriteHeader(t.Status)
}
if t.Component != nil {
return t.Component.Render(t.Ctx, w)
}
return nil
}
// WriteContentType writes writes the content type.
func (t TemplRender) WriteContentType(w http.ResponseWriter) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}