模板渲染

模板渲染

Context#Render(code int, name string, data interface{}) error 用于渲染一个模板,然后发送一个 text/html 的状态响应。我们可以使用任何模板引擎,只要赋值给 Echo.Renderer

下面是使用Go html/template 的示例:

1.实现 echo.Renderer 接口

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.预编译模板

public/views/hello.html

{{define "hello"}}Hello, {{.}}!{{end}}

 

t := &Template{
	templates: template.Must(template.ParseGlob("public/views/*.html")),
}

3.注册模板

e := echo.New()
e.Renderer = t
e.GET("/hello", Hello)

4.在 action 中渲染模板

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

 

posted @ 2019-05-25 01:00  Jin同学  阅读(171)  评论(0)    收藏  举报