清风徐来
Michael's Blog
Demo 学 Echo Part6 模板渲染

请输入图片描述 echo解析和呈现模板的过程不是由自身处理,而是由html/template包处理。因此,echo中的模板渲染方式与使用普通golang应用程序相同.

package main

import (
	"html/template"
	"io"
	"net/http"

	"github.com/labstack/echo"
)

type M map[string]interface{}

type Info struct {
	Affiliation string
	Address     string
}

func (t Info) GetAffiliationDetailInfo() string {
	return "have 31 divisions"
}

type Person struct {
	Name    string
	Gender  string
	Hobbies []string
	Info    Info
}

//.template属性负责解析和呈现模板
//.location属性指向模板文件所在的文件夹路径。
// debug 如果为false,则模板解析仅在应用程序启动时执行一次。此模式适合在生产阶段激活
type Renderer struct {
	template *template.Template
	debug    bool
	location string
}

//创建NewRenderer()函数,以便更容易初始化渲染器对象
func NewRenderer(location string, debug bool) *Renderer {
	tpl := new(Renderer)
	tpl.location = location
	tpl.debug = debug

	tpl.ReloadTemplates()

	return tpl
}

//为struct renderer准备两个方法,即ReloadTemplates()和.Render()

//ReloadTemplates方法用于解析模板。初始化渲染器对象时必须调用此方法。
//如果.debug == true,则每次访问路径时都必须调用此方法
func (t *Renderer) ReloadTemplates() {
	t.template = template.Must(template.ParseGlob(t.location))
}

func (t *Renderer) Render(
	w io.Writer,
	name string,
	data interface{},
	c echo.Context,
) error {
	if t.debug {
		t.ReloadTemplates()
	}

	return t.template.ExecuteTemplate(w, name, data)
}

func main() {
	e := echo.New()

	e.Renderer = NewRenderer("./*.html", true)

	e.GET("/index", func(c echo.Context) error {
		data := M{"message": "Hello World!"}
		return c.Render(http.StatusOK, "index.html", data)
	})

	e.GET("/user", func(c echo.Context) error {
		person := Person{
			Name:    "Bruce",
			Gender:  "male",
			Hobbies: []string{"Reading Books", "Traveling", "Buying things"},
			Info:    Info{"Julin Enterprises", "Suzhou City"},
		}
		return c.Render(http.StatusOK, "user.html", person)
	})

	e.Logger.Fatal(e.Start(":9000"))
}

index.html 如下:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        Message from index: {{.message}}!
    </body>
</html>

更复杂的user.html

<html>
    <head>
        <title>Learning html/template Actions</title>
    </head>
    <body>
        <table>
                <tr>
                    {{/* example how to use actions */}}
                    <td>{{"姓名"}}</td>
                    <td>: {{.Name}}</td>
                </tr>

                <tr>
                    <td>性别</td>
                    {{$gender := .Gender}}
                    <td style="text-transform: capitalize;">: 
                        {{$gender}}
                    </td>
                </tr>

                <tr>
                    <td>爱好</td>
                    <td>: 
                        {{range $index, $elem := .Hobbies}}
                            {{$elem}},
                        {{end}}
                    </td>
                </tr>

                <tr>
                    <td>联系</td>
                    <td>: {{.Info.Affiliation}} ({{.Info.GetAffiliationDetailInfo}})</td>
                </tr>
                {{with .Info}}
                <tr>
                    <td>Address</td>
                    <td>: {{.Address}}</td>
                </tr>
                {{end}}

                {{if eq .Name "Bruce"}}
                <tr>
                    <td colspan="2" style="font-weight: bold;">
                        Ooooh,Bruce!
                    </td>
                </tr>
                {{end}}
        </table>
    </body>
</html>

测试一下:

curl http://localhost:9000/index
<!DOCTYPE html>
<html>
    <head>
        <title></title>
    </head>
    <body>
        Message from index: Hello World!!
    </body>
</html>

curl http://localhost:9000/user
<html>
    <head>
        <title>Learning html/template Actions</title>
    </head>
    <body>
        <table>
                <tr>
                    
                    <td>姓名</td>
                    <td>: Bruce</td>
                </tr>

                <tr>
                    <td>性别</td>
                    
                    <td style="text-transform: capitalize;">: 
                        male
                    </td>
                </tr>

                <tr>
                    <td>爱好</td>
                    <td>: 
                        
                            Reading Books,
                        
                            Traveling,
                        
                            Buying things,
                        
                    </td>
                </tr>

                <tr>
                    <td>联系</td>
                    <td>: Julin Enterprises (have 31 divisions)</td>
                </tr>
                
                <tr>
                    <td>Address</td>
                    <td>: Suzhou City</td>
                </tr>
                

                
                <tr>
                    <td colspan="2" style="font-weight: bold;">
                        Ooooh,Bruce!
                    </td>
                </tr>
                
        </table>
    </body>
</html>

最后修改于 2019-08-17