Template
Rendering
In handler functions, we can use the context method Context#Render(code int, name string, data any) error to render our template files into HTML code and respond to the client.
However, before doing so, we must register a template engine by setting the Slim instance property Slim#Renderer.
Slim allows us to use any template engine to implement template rendering functionality, as long as we implement the following interface:
type Renderer interface { Render(c slim.Context, w io.Writer, name string, data any) error}The example below demonstrates how to implement a template engine using Go’s standard library html/template package:
-
Implement the interface
slim.RendererImplement template enginetype Template struct { templates *template.Template}func (t *Template) Render(c slim.Context, w io.Writer, name string, data any) error { return t.templates.ExecuteTemplate(w, name, data)} -
Pre-compile templates
views/hello.html{{define "hello"}}Hello, {{.}}!{{end}}Pre-compile templatest := &Template{ templates: template.Must(template.ParseGlob("views/*.html")),} -
Register templates
Register templatess := slim.New() s.Renderer = t s.GET("/hello", Hello) -
Render template in handler
Render templatefunc Hello(c slim.Context) error { return c.Render(http.StatusOK, "hello", "World")}
Enhancement
In some cases, it may be useful to generate URIs from templates. To do this, you need to call from the template itself. Golang’s standard library html/template is not well-suited for this task, but this can be accomplished in two ways: providing a common method on all objects passed to the template, or passing and enhancing this object in a custom renderer. Given the flexibility of the latter approach, here is an example program:
<html> <body> <h1>Hello {{index . "name"}}</h1> <p> {{ with $x := index . "reverse" }} {{ call $x "foobar" }} <-- this will call the $x with parameter "foobar" {{ end }} </p> </body></html>Our server code:
package mainimport ( "html/template" "io" "log" "net/http" "go-slim.dev/slim")// TemplateRenderer is a custom html/template renderer for Echo frameworktype TemplateRenderer struct { templates *template.Template}// Render renders a template documentfunc (t *TemplateRenderer) Render(c slim.Context, w io.Writer, name string, data interface{}) error { // Add global methods if data is a map if viewContext, isMap := data.(map[string]interface{}); isMap { viewContext["reverse"] = c.Slim().Reverse } return t.templates.ExecuteTemplate(w, name, data)}func main() { s := slim.New() renderer := &TemplateRenderer{ templates: template.Must(template.ParseGlob("*.html")), } s.Renderer = renderer // Named route "foobar" s.GET("/something", func(c slim.Context) error { return c.Render(http.StatusOK, "template.html", map[string]any{ "name": "Dolly!", }) }).Name = "foobar" log.Fatal(s.Start(":8000"))}