龙空技术网

Go语言Echo Web框架6-模板

enjoyGo 69

前言:

此刻姐妹们对“echohtml代码”可能比较注意,朋友们都需要分析一些“echohtml代码”的相关文章。那么小编在网络上收集了一些关于“echohtml代码””的相关内容,希望看官们能喜欢,大家一起来了解一下吧!

上一节:Go语言Echo Web框架5-静态文件

模板渲染

使用echo.Context的Render函数渲染数据到模板,发送text/html响应。模板的注册使用echo.Renderer函数,允许用户使用任何模板引擎。

模板渲染

通过下面的例子,我们可以知道怎么使用go的html模板。

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}}  // main.go  t := &Template{    templates: template.Must(template.ParseGlob("public/views/*.html")),}

3.注册模板

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

4.在handler中渲染模板

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

现在的开发模式,都是前后端分离的模式开发,使用模板渲染的开发不是很常用。本节可以做个大致的了解。

单从web前端的角度,也许会认为后端模版引擎没用途了,可以丢弃了,但是在渲染邮件,渲染配置,自动生成代码还是有用处的,模板渲染还是需要了解下。

下一节:Go语言Echo Web框架7-Cookie和Session

标签: #echohtml代码