Go HTML/template 模板使用方法
背景说明
html/template 它是 Go 官方维护的,但是在初次接触的时候,缺乏文档指南,看了很多零碎的相关资料,大概知道了 {{ . }}
的用法,翻看 官方DOC ...没办法立马给到我想要的答案:如何模版复用、循环渲染(慢慢研究可能会得到答案)... 所以本篇文章的是关于模版复用的实现尝试.要获取更详细的用法,可以看这篇文章go html模板的使用
模版复用
1 在模版内,使用 {{ define "名称" }}
内容 {{ end }}
定义模版,如:
{{ define "header" }}
<!doctype html>
<html lang="">
<head>
<title>定义头</title>
</head>
<body>
{{ end }}
{{ define "footer" }}
</body>
</html>
{{ end }}
2 再需要引用的模版内,使用 {{ template "名称" . }}
,引用模版,注意 .
别漏了,如:
{{ template "header" . }}
<h1>Hello world</h1>
{{ template "footer" . }}
以上就是模版复用的方法,实际在官方文档有相关介绍,但它只介绍了轮子,没告诉我们轮子使用范围:
import "html/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")
你看到这个例子,能立马想到模版里面如何复用吗?反正我是不能!
渲染数据
主要是通过 {{ . }}
,下面以我目前所了解的用法分享给大家:
1.直接渲染值:
...
<h1>{{ .name }}</h1>
...
2.加入语法(还有其它语法,只是指条路):
...
<ul>
{{ range .Listdata }}
<li>{{ .Title }} </li>
{{ end }}
</ul>
...
{{ . }} 用法
1.使用 .
访问当前数据域:比如 range 里使用 .
访问的其实是循环项的数据域:
// 伪代码 传递的数据
Listdata := []struct {
Title string
Nickname string
}{{Title: "gang", Nickname: "sdfsf"},
{Title: "gang", Nickname: "sdfsf"}})
ctx.View("test.html")
}
...
<ul>
{{ range .Listdata }}
这个时候, . 范围在 Listdata 数据域,所以可以使用 . 来访问对应字段
<li>{{ .Title }} </li>
{{ end }}
</ul>
...
- 使用 $. 访问绝对顶层数据域:
// 伪代码 传递的数据
Age := 12
Listdata := []struct {
Title string
Nickname string
}{{Title: "gang", Nickname: "sdfsf"},
{Title: "gang", Nickname: "sdfsf"}})
ctx.View("test.html")
}
...
<ul>
{{ range .Listdata }}
这个时候, . 范围在 Listdata 数据域,所以可以使用 . 来访问对应字段
<li>{{ .Title }} ---> {{ $.Age }}</li>
{{ end }}
</ul>
...
使用 Iris 框架实际运用
-
文件目录结构
main.go └── views ├── layouts │ ├── layout_test.html ├── test.html
-
main.go 代码
package main import ( "github.com/kataras/iris" ) func main() { app := iris.New() app.RegisterView(iris.HTML("./views", ".html").Reload(true)) app.Get("/", func(ctx iris.Context) { ctx.ViewData("Age", 12) ctx.ViewData("Listdata", []struct { Title string Nickname string }{{Title: "gang", Nickname: "sdfsf"}, {Title: "gang", Nickname: "sdfsf"}}) ctx.View("test.html") }) app.Run(iris.Addr(":8080")) }
-
layout_test.html 代码
{{ define "headertest" }} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Hello</title> </head> <body> {{ end }} {{ define "footertest" }} </body> </html> {{ end }}
-
test.html 代码
{{ template "headertest" . }} <h1>Hello world</h1> <ul> {{ range .Listdata }} <li>{{ .Title }} {{ $.Age }}</li> {{ end }} </ul> {{ template "footertest" . }}
-
运行
$ go run main.go Now listening on: http://localhost:8080 Application started. Press CMD+C to shut down.
-
浏览器
其它文档
本文介绍只是冰山一角,可能还有其它更好的方法等待着我们发现,在发表本文之前,除了官方doc, 还主要参考了:
- Go html/template 模板的使用实例详解
- 视图(模板引擎)
- 重点推荐食用这篇文章 [go html模板的使用]
本作品采用《CC 协议》,转载必须注明作者和本文链接
感觉跟PHP的smarty有点像