2016-10-20 20:30:53 +02:00
|
|
|
+++
|
|
|
|
title = "Templates"
|
|
|
|
description = "How to use templates in Echo"
|
2016-11-21 00:16:22 +02:00
|
|
|
[menu.main]
|
2016-10-20 20:30:53 +02:00
|
|
|
name = "Templates"
|
|
|
|
parent = "guide"
|
|
|
|
weight = 3
|
|
|
|
+++
|
|
|
|
|
2016-11-17 08:46:00 +02:00
|
|
|
## Template Rendering
|
2016-10-20 20:30:53 +02:00
|
|
|
|
|
|
|
`Context#Render(code int, name string, data interface{}) error` renders a template
|
|
|
|
with data and sends a text/html response with status code. Templates can be registered
|
|
|
|
using `Echo.SetRenderer()`, allowing us to use any template engine.
|
|
|
|
|
|
|
|
Example below shows how to use Go `html/template`:
|
|
|
|
|
|
|
|
1. Implement `echo.Renderer` interface
|
|
|
|
|
|
|
|
```go
|
|
|
|
type Template struct {
|
|
|
|
templates *template.Template
|
|
|
|
}
|
|
|
|
|
|
|
|
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
|
|
|
|
return t.templates.ExecuteTemplate(w, name, data)
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
2. Pre-compile templates
|
|
|
|
|
|
|
|
`public/views/hello.html`
|
|
|
|
|
|
|
|
```html
|
|
|
|
{{define "hello"}}Hello, {{.}}!{{end}}
|
|
|
|
```
|
|
|
|
|
|
|
|
```go
|
|
|
|
t := &Template{
|
|
|
|
templates: template.Must(template.ParseGlob("public/views/*.html")),
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
3. Register templates
|
|
|
|
|
|
|
|
```go
|
|
|
|
e := echo.New()
|
2016-10-26 01:56:12 +02:00
|
|
|
e.Renderer = t
|
2016-10-20 20:30:53 +02:00
|
|
|
e.GET("/hello", Hello)
|
|
|
|
```
|
|
|
|
|
|
|
|
4. Render a template inside your handler
|
|
|
|
|
|
|
|
```go
|
|
|
|
func Hello(c echo.Context) error {
|
|
|
|
return c.Render(http.StatusOK, "hello", "World")
|
|
|
|
}
|
|
|
|
```
|