6_模板与渲染.md
Gin模板和渲染
模板语法
{{ . }} 取值
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello</title> </head> <body> <p>Hello {{.Name}}</p> <p>性别:{{.Gender}}</p> <p>年龄:{{.Age}}</p> </body> </html>
注释 {{/* */}}
{{/* a comment */}} 注释,执行时会忽略。可以多行。注释不能嵌套,并且必须紧贴分界符始止。
pipeline |
pipeline
是指产生数据的操作。比如{{.}}
、{{.Name}}
等。Go的模板语法中支持使用管道符号|
链接多个命令,用法和unix下的管道类似:|
前面的命令会将运算结果(或返回值)传递给后一个命令的最后一个位置。
变量
$obj := {{ . }}
移除空格 {{- .Name -}}
我们在使用模板语法的时候会不可避免的引入一下空格或者换行符,这样模板最终渲染出来的内容可能就和我们想的不一样,这个时候可以使用{{-
语法去除模板内容左侧的所有空白符号, 使用-}}
去除模板内容右侧的所有空白符号。
条件判断 if
{{if pipeline}} T1 {{end}} {{if pipeline} T1 {{else}} T0 {{end}} {{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
迭代range
Go的模板语法中使用range
关键字进行遍历,有以下两种写法,其中pipeline
的值必须是数组、切片、字典或者通道。
{{range pipeline}} T1 {{end}} 如果pipeline的值其长度为0,不会有任何输出 {{range pipeline}} T1 {{else}} T0 {{end}} 如果pipeline的值其长度为0,则会执行T0。
with 初始化判断
{{with pipeline}} T1 {{end}} 如果pipeline为empty不产生输出,否则将dot设为pipeline的值并执行T1。不修改外面的dot。 {{with pipeline}} T1 {{else}} T0 {{end}} 如果pipeline为empty,不改变dot并执行T0,否则dot设为pipeline的值并执行T1。
预定义函数
执行模板时,函数从两个函数字典中查找:首先是模板函数字典,然后是全局函数字典。一般不在模板内定义函数,而是使用Funcs方法添加函数到模板里。
预定义的全局函数:
and 函数返回它的第一个empty参数或者最后一个参数; 就是说"and x y"等价于"if x then y else x";所有参数都会执行; or 返回第一个非empty参数或者最后一个参数; 亦即"or x y"等价于"if x then x else y";所有参数都会执行; not 返回它的单个参数的布尔值的否定 len 返回它的参数的整数类型长度 index 执行结果为第一个参数以剩下的参数为索引/键指向的值; 如"index x 1 2 3"返回x[1][2][3]的值;每个被索引的主体必须是数组、切片或者字典。 print 即fmt.Sprint printf 即fmt.Sprintf println 即fmt.Sprintln html 返回与其参数的文本表示形式等效的转义HTML。 这个函数在html/template中不可用。 urlquery 以适合嵌入到网址查询中的形式返回其参数的文本表示的转义值。 这个函数在html/template中不可用。 js 返回与其参数的文本表示形式等效的转义JavaScript。 call 执行结果是调用第一个参数的返回值,该参数必须是函数类型,其余参数作为调用该函数的参数; 如"call .X.Y 1 2"等价于go语言里的dot.X.Y(1, 2); 其中Y是函数类型的字段或者字典的值,或者其他类似情况; call的第一个参数的执行结果必须是函数类型的值(和预定义函数如print明显不同); 该函数类型值必须有1到2个返回值,如果有2个则后一个必须是error接口类型; 如果有2个返回值的方法返回的error非nil,模板执行会中断并返回给调用模板执行者该错误;
比较函数
布尔函数会将任何类型的零值视为假,其余视为真。
下面是定义为函数的二元比较运算的集合:
eq 如果arg1 == arg2则返回真 ne 如果arg1 != arg2则返回真 lt 如果arg1 < arg2则返回真 le 如果arg1 <= arg2则返回真 gt 如果arg1 > arg2则返回真 ge 如果arg1 >= arg2则返回真
为了简化多参数相等检测,eq(只有eq)可以接受2个或更多个参数,它会将第一个参数和其余参数依次比较,返回下式的结果:
{{eq arg1 arg2 arg3}}
比较函数只适用于基本类型(或重定义的基本类型,如”type Celsius float32”)。但是,整数和浮点数不能互相比较。
自定义函数
// 自定义一个夸人的模板函数 kua := func(arg string) (string, error) { return arg + "真帅", nil } // 采用链式操作在Parse之前调用Funcs添加自定义的kua函数 tmpl, err := template.New("hello").Funcs(template.FuncMap{"kua": kua}).Parse(string(htmlByte)) if err != nil { fmt.Println("create template failed, err:", err) return }
可以在模板文件hello.tmpl
中按照如下方式使用我们自定义的kua
函数了。
{{kua .Name}}
嵌套template
-
嵌套单独文件模板
{{template "ul.tmpl"}} -
嵌套
define
定义的模板{{define "define.tmpl"}} .... {{end}} {{template "define.tmpl"}}
注意:在解析模板时,被嵌套的模板一定要在方面解析。
tmpl, err := template.ParseFiles("./t.tmpl", "./ul.tmpl"
block
{{block "name" pipeline}} T1 {{end}}
block
是定义模板{{define "name"}} T1 {{end}}
和执行{{template "name" pipeline}}
缩写,典型的用法是定义一组根模板,然后通过在其中重新定义块模板进行自定义。
定义一个根模板templates/base.tmpl
,内容如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>Go Templates</title> </head> <body> <div class="container-fluid"> {{block "content" . }}{{end}} </div> </body> </html>
然后定义一个templates/index.tmpl
,”继承”base.tmpl
:
{{template "base.tmpl"}} {{define "content"}} <div>Hello world!</div> {{end}}
然后使用template.ParseGlob
按照正则匹配规则解析模板文件,然后通过ExecuteTemplate
渲染指定的模板:
func index(w http.ResponseWriter, r *http.Request){ tmpl, err := template.ParseGlob("templates/*.tmpl") if err != nil { fmt.Println("create template failed, err:", err) return } err = tmpl.ExecuteTemplate(w, "index.tmpl", nil) if err != nil { fmt.Println("render template failed, err:", err) return } }
冲突
模板名字冲突
如果我们的模板名称冲突了,例如不同业务线下都定义了一个index.tmpl
模板,我们可以通过下面两种方法来解决。
- 在模板文件开头使用
{{define 模板名}}
语句显式的为模板命名。 - 可以把模板文件存放在
templates
文件夹下面的不同目录中,然后使用template.ParseGlob("templates/**/*.tmpl")
解析模板。
标识符({{ }})冲突
Go标准库的模板引擎使用的花括号{{
和}}
作为标识,而许多前端框架(如Vue
和 AngularJS
)也使用{{
和}}
作为标识符,所以当我们同时使用Go语言模板引擎和以上前端框架时就会出现冲突,这个时候我们需要修改标识符,修改前端的或者修改Go语言的。
template.New("test").Delims("{[", "]}").ParseFiles("./t.tmpl"
html/template
html/template
包实现了数据驱动的模板,用于生成可防止代码注入的安全的HTML内容。它提供了和text/template
包相同的接口,Go语言中输出HTML的场景都应使用html/template
这个包。
要求
Go语言内置了文本模板引擎text/template
和用于HTML文档的html/template
。模板要求如下:
- 后缀通常
tmpl
和tpl
。也可以任意。 - 编码必须为UTF-8
- 使用
{{}}
标识数据 - 传给模板这样的数据就可以通过点号(
.
)来访问,如果数据是复杂类型的数据,可以通过{ { .FieldName }}来访问它的字段。 - 除数据外,其他原样输出
模板引擎的使用
定义模板文件
定义模板文件需要按相关语法。
解析模板文件
func (t *Template) Parse(src string) (*Template, error) func ParseFiles(filenames ... string) (*Template, error) func ParseGlob(pattern string) (*Template, error)
渲染模板
func (t *Template) Execute(w io.Writer, data interface{}) error func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{})
// main.go type UserInfo struct { Name string Gender string Age int } func sayHello(w http.ResponseWriter, r *http.Request) { // 解析指定文件生成模板对象 tmpl, err := template.ParseFiles("./hello.tmpl") if err != nil { fmt.Println("create template failed, err:", err) return } // 利用给定数据渲染模板,并将结果写入w user := UserInfo{ Name: "小王子", Gender: "男", Age: 18, } tmpl.Execute(w, user) }
text/template与html/tempalte的区别
html/template
针对的是需要返回HTML内容的场景,在模板渲染过程中会对一些有风险的内容进行转义,以此来防范跨站脚本攻击。
例如,我定义下面的模板文件:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Hello</title> </head> <body> {{.}} </body> </html>
这个时候传入一段JS代码并使用html/template
去渲染该文件,会在页面上显示出转义后的JS内容。 <script>alert('嘿嘿嘿')</script>
这就是html/template
为我们做的事。
但是在某些场景下,我们如果相信用户输入的内容,不想转义的话,可以自行编写一个safe函数,手动返回一个template.HTML
类型的内容。示例如下:
func xss(w http.ResponseWriter, r *http.Request){ tmpl,err := template.New("xss.tmpl").Funcs(template.FuncMap{ "safe": func(s string)template.HTML { return template.HTML(s) }, }).ParseFiles("./xss.tmpl") if err != nil { fmt.Println("create template failed, err:", err) return } jsStr := `<script>alert('嘿嘿嘿')</script>` err = tmpl.Execute(w, jsStr) if err != nil { fmt.Println(err) } }
这样我们只需要在模板文件不需要转义的内容后面使用我们定义好的safe函数就可以了。
{{ . | safe }}
Gin模板
HTML渲染
Gin框架中使用LoadHTMLGlob()
或者LoadHTMLFiles()
方法进行HTML模板渲染。
func main() { r := gin.Default() r.LoadHTMLGlob("templates/**/*") //r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html") r.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.html", gin.H{ "title": "posts/index", }) }) r.GET("users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.html", gin.H{ "title": "users/index", }) }) r.Run(":8080") }
自定义函数
SetFuncMap()
func main() { router := gin.Default() router.SetFuncMap(template.FuncMap{ "safe": func(str string) template.HTML{ return template.HTML(str) }, }) router.LoadHTMLFiles("./index.tmpl") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", "<a href='https://liwenzhou.com'>李文周的博客</a>") }) router.Run(":8080") }
静态文件处理
Static()
func main() { r := gin.Default() r.Static("/static", "./static") r.LoadHTMLGlob("templates/**/*") // ... r.Run(":8080") }
JSON渲染
func main() { r := gin.Default() // gin.H 是map[string]interface{}的缩写 r.GET("/someJSON", func(c *gin.Context) { // 方式一:自己拼接JSON c.JSON(http.StatusOK, gin.H{"message": "Hello world!"}) }) r.GET("/moreJSON", func(c *gin.Context) { // 方法二:使用结构体 var msg struct { Name string `json:"user"` Message string Age int } msg.Name = "小王子" msg.Message = "Hello world!" msg.Age = 18 c.JSON(http.StatusOK, msg) }) r.Run(":8080") }
YMAL渲染
r.GET("/someYAML", func(c *gin.Context) { c.YAML(http.StatusOK, gin.H{"message": "ok", "status": http.StatusOK}) })
protobuf渲染
r.GET("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // protobuf 的具体定义写在 testdata/protoexample 文件中。 data := &protoexample.Test{ Label: &label, Reps: reps, } // 请注意,数据在响应中变为二进制数据 // 将输出被 protoexample.Test protobuf 序列化了的数据 c.ProtoBuf(http.StatusOK, data) })
本文作者:nsfoxer
本文链接:https://www.cnblogs.com/nsfoxer/p/16317582.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步