1
0
mirror of https://github.com/labstack/echo.git synced 2025-03-03 14:52:47 +02:00
echo/website/content/guide/templates.md
Antonio Pagano 966839dfea Updating guides to according to V3 Codebase (#691)
* [doc] adding graceful documentation and example.

* adding myself to the maintainers list and minor comment formatting change

* [doc] updating code on the guides/context.md and guides/cookies.md to use v3 code.

* [doc] updating error-handling and request to v3 codebase

* [doc] updating templates documentation
2016-10-25 16:56:12 -07:00

1.2 KiB

+++ title = "Templates" description = "How to use templates in Echo" [menu.side] name = "Templates" parent = "guide" weight = 3 +++

Templates

Template Rendering

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

    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

    {{define "hello"}}Hello, {{.}}!{{end}}
    
    t := &Template{
        templates: template.Must(template.ParseGlob("public/views/*.html")),
    }
    
  3. Register templates

    e := echo.New()
    e.Renderer = t
    e.GET("/hello", Hello)
    
  4. Render a template inside your handler

    func Hello(c echo.Context) error {
    	return c.Render(http.StatusOK, "hello", "World")
    }