Gin HTML渲染语法

2022-11-07

最近用Gin框架写了自己的博客,在渲染HTML模板的时候踩了一些坑,因为官方文档写的非常简单,所以借这个机会把常用的语法整理出来供大家参考。

变量

变量使用{{}}标记,.表示当前变量,如{{ .title }},则渲染gin.H中定义的title属性,看官方完整例子:

main.go

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("templates/*")
	//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
	router.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			"title": "Main website",
		})
	})
	router.Run(":8080")
}

templates/index.tmpl

<html>
	<h1>
		{{ .title }}
	</h1>
</html>

循环

range关键字支持遍历切片(slice)和字典(map),语法如下:

{{range $i,$v := .list}}
	{{$i}} ==> {{$v}}
{{end}}

也可以这样遍历:

{{range .list}}
	{{ .field }}
{{end}}

如果要在循环内访问循环外变量,则需要通过$.访问:

{{range $i,$v := .list}}
	{{$.title}}
{{end}}

判断

判断通过if关键字来实现,支持与或非:

{{if .cond1 and .cond2}}
	{{.dosth1}}
{{else if not .cond3}}
	{{.dosth2}}
{{else}}
	{{.dosth3}}
{{end}}

比较

比较支持>,>=,==,!=,<=,<,请看代码:

{{if gt .a .b}}
	{{.dosth}}
{{end}}
{{if ge .a .b}}
	{{.dosth}}
{{end}}
{{if eq .a .b}}
	{{.dosth}}
{{end}}
{{if ne .a .b}}
	{{.dosth}}
{{end}}
{{if le .a .b}}
	{{.dosth}}
{{end}}
{{if lt .a .b}}
	{{.dosth}}
{{end}}

上面这些内容就是模板中比较常见的用法了,其中各种用法来自网络中查到的各种文章并结合自己的实践整理而成(扒拉了半天源码没找到在哪实现的,等找到了再继续填坑),除了上面提到的这些用法,还有模板继承等使用方法(需要引用第三方库),等下次我们再分享。