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

Rendering XHTML pages #2739

Closed
Tachi107 opened this issue Jan 24, 2025 · 2 comments
Closed

Rendering XHTML pages #2739

Tachi107 opened this issue Jan 24, 2025 · 2 comments

Comments

@Tachi107
Copy link

Hi!

Echo's template rendering support currently unconditionally sends HTML pages with the text/html media type to the client. This is documented in the Render function.

My HTML fragments, though, use the XML syntax of HTML, also known as XHTML. This means that, for example, they lack a DOCTYPE declaration and the xml:lang attribute is used instead of lang, which makes them invalid HTML documents when sent with the text/html media type.

Is it possible to serve them with the application/xhtml+xml media type? If not, could an option to do this please be added?

Thanks!

@aldas
Copy link
Contributor

aldas commented Jan 24, 2025

something like that.

package main

import (
	"github.com/labstack/echo/v4"
	"html/template"
	"io"
	"log/slog"
	"net/http"
)

type XHTMLRenderer struct {
	Template interface {
		ExecuteTemplate(wr io.Writer, name string, data any) error
	}
}

func (t *XHTMLRenderer) Render(w io.Writer, name string, data any, c echo.Context) error {
	c.Response().Header().Set(echo.HeaderContentType, "application/xhtml+xml") // or here
	return t.Template.ExecuteTemplate(w, name, data)
}

func main() {
	e := echo.New()
	e.Renderer = &XHTMLRenderer{
		Template: template.Must(template.ParseGlob("../*.html")),
	}

	e.GET("/", func(c echo.Context) error {
		//c.Response().Header().Set(echo.HeaderContentType, "application/xhtml+xml") // here
		return c.Render(http.StatusOK, "index.html", nil)
	})

	if err := e.Start(":8080"); err != nil {
		slog.Error("failed to start server")
	}
}

both work because eventually this method is called and it will not set content type if it is already set

echo/context.go

Lines 243 to 248 in ce0b12a

func (c *context) writeContentType(value string) {
header := c.Response().Header()
if header.Get(HeaderContentType) == "" {
header.Set(HeaderContentType, value)
}
}

@Tachi107
Copy link
Author

Makes sense! I like the XHTMLRenderer.Render() solution more. Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants