本文摘自网络,作者pywee,侵删。
gtpl 可以灵活的替代 html/template 包。变量和函数调用更加方便。支持 if else elseif
a.go 文件
data := &Dat a{
Id: 1,
WebTitle: "WebTitle",
Winner: &Demo{
Str: "pywee",
},
Users: []*User{
{
Id: 1,
UserName: "Jim",
MyList: []*UserCustom{
{PhoneNumber: "1"},
{PhoneNumber: "2"},
},
},
{
Id: 2,
UserName: "Lucy",
MyList: []*UserCustom{
{PhoneNumber: "1"},
{PhoneNumber: "2"},
},
},
},
}
// http server example
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
// 实例化gtpl (instantiation gtpl)
p := templates.NewParser()
// 引入模板文件,将 data 数据匹配模板中的调用
re, err := p.ParseFile("index.html", data)
if err != nil {
panic(err)
}
// print string
// fmt.Println(re.String())
// 输出到屏幕,它的作用相当于 template.Excute(w, "%s", data)
re.Fprint(w)
})
index.html
// 访问Id 和 WebTitle字段
{:id}
{:web_title}
// 访问 Data 结构体中的 Other.Demo.Str
// to call Other.Demo.Str of struct Data
{:winner.str}
// 在访问字段的同时,执行内置函数
{:trim(replace(title, "i am", "xx", -1), "xx")}
// 对于列表处理,例如循环 data 下的 users 数组,用如下方式
{:id}
{:winner.str} // 访问 Data 下的 Winner结构体,再访问该结构体下的 Str 字段
{!list:users}
{!if id==(1*1+1-1-1)}
man: {:user_name}
{;elseif 1==21}
women: {:user_name}
{;else}
{!list:my_list}
{:phone_number}
{/list}
{/if}
{/list}
</html>
https://github.com/pywee/gtpl
相关阅读 >>
python、Golang、java、c++哪个薪资高?小白必看!
rabbitmq 消息丢失处理机制 confirm模式 [Go 版本]
如何读取yaml,json,ini等配置文件【Golang 入门系列九】
更多相关阅读请进入《Go》频道 >>

Go语言101
一个与时俱进的Go编程知识库。