Gin HTML 模板与数据的渲染

Gin HTML 模板与数据的渲染

1. HTML 模板渲染

1.1 全部模板放在一个目录里面的配置方法

1. 我们首先在项目根目录新建 templates 文件夹,然后在文件夹中新建 index.html

<!DOCTYPE html> 
<html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title>
</head> 
<body>
  <h1>这是一个 html 模板</h1>
  <h3>{{.title}}</h3> </body>
</html>

2. Gin 框架中使用 c.HTML 可以渲染模板,渲染模板前需要使用 LoadHTMLGlob()或者 LoadHTMLFiles()方法加载模板。

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	//r.LoadHTMLGlob("templates/*")
	r.LoadHTMLFiles("./templates/index.html")
	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title":  "Main website",
			"name":   "admin",
			"pwd":    "123456666",
			"title1": "前台首页",
		})
	})
	r.GET("/h", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{
			"title2": "Main website",
		})
	})
	r.Run()
}

运行上述代码,并在浏览器中访问127.0.0.1:8080/demo

1.2 模板放在不同目录里面的配置方法

Gin 框架中如果不同目录下面有同名模板的话我们需要使用下面方法加载模板 注意:定义模板的时候需要通过 define 定义名称

templates/admin/index.html
<!– 相当于给模板定义一个名字 define end 成对出现–>

{{ define "admin/index.html" }}
<!DOCTYPE html> 
<html lang="en"> 
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>Document</title>
</head> 
<body>
    <h1>后台首页</h1>
    <h3>{{.title}}</h3>
</body>
</html>
{{ end }}

templates/default/index.html

<!– 相当于给模板定义一个名字 define end 成对出现–>

{{ define "default/index.html" }} <!DOCTYPE html>
<html lang="en"> <head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title>
</head> <body>
<h1>前台模板</h1>
<h3>{{.title}}</h3> </body>
</html> {{end}}

业务逻辑

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.LoadHTMLGlob("templates/**/*")

	r.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "default/index.html", gin.H{
			"title":  "Main website",
			"name":   "admin",
			"pwd":    "123456666",
			"title1": "前台首页",
		})
	})
	
	r.GET("/admin", func(c *gin.Context) {
		c.HTML(http.StatusOK, "admin/index.html", gin.H{
			"title2": "Main website",
		})
	})
	r.Run()
}

注意:如果模板在多级目录里面的话需要这样配置 r.LoadHTMLGlob(“templates/**/**/*”) /** 表示目录

2. Gin 模板基本语法

2.1 输出数据使用{{.}}

模板语法都包含在{{和}}中间,其中{{.}}中的点表示当前对象。 当我们传入一个结构体对象时,我们可以根据.来访问结构体的对应字段。例如: 业务逻辑

package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	Name   string
	Gender string
	Age    int
}

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("templates/**/*")
	user := UserInfo{
		Name:   "张三",
		Gender: "男",
		Age:    18,
	}
	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "default/gin.html", map[string]interface{}{
			"title": "前台首页",
			"user":  user,
		})
	})
	router.Run()
}

模板

<!– 相当于给模板定义一个名字 define end 成对出现–>

{{ define "default/gin.html" }}
<!DOCTYPE html> 
<html lang="en"> 
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>Document</title>
</head> 
<body>
    <h1>前台首页</h1>
    <h3>{{.title}}</h3>
    <h3>{{.user.Name}}</h3>
    <h3>{{.user.Age}}</h3>
    <h3>{{/*.user.Gender*/}}</h3>
</body>
</html>
{{ end }}

2.2 注释

{{/* a comment */}}

注释,执行时会忽略。可以多行。注释不能嵌套,并且必须紧贴分界符始止。

例如上面注释

 <h3>{{/*.user.Gender*/}}</h3>

2.3 变量

我们还可以在模板中声明变量,用来保存传入模板的数据或其他语句生成的结果。具体语法

如下:

<h4>{{$obj := .title}}</h4>

输出:

<h4>{{$obj}}</h4>

完整如下:

{{ define "default/gin.html" }}
<!DOCTYPE html> 
<html lang="en"> 
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> 
<title>Document</title>
</head> 
<body>
    <h1>前台首页</h1>
    <h3>{{.title}}</h3>
    <h4>{{$obj := .title}}</h4>
    <h4>{{$obj}}</h4>
    <h3>{{.user.Name}}</h3>
    <h3>{{.user.Age}}</h3>     
    <h3>{{/*.user.Gender*/}}</h3>
</body>
</html>
{{ end }}

2.4 移除空格

有时候我们在使用模板语法的时候会不可避免的引入一下空格或者换行符,这样模板最终渲 染出来的内容可能就和我们想的不一样,这个时候可以使用{{-语法去除模板内容左侧的所有 空白符号, 使用-}}去除模板内容右侧的所有空白符号。

例如:

{{- .Name -}}

注意:-要紧挨{{和}},同时与模板值之间需要使用空格分隔。

2.5 比较函数

布尔函数会将任何类型的零值视为假,其余视为真。

下面是定义为函数的二元比较运算的集合:

eq如果arg1 == arg2则返回真
ne如果arg1 != arg2则返回真
lt如果arg1 < arg2则返回真
le如果arg1 <= arg2则返回真
gt如果arg1 > arg2则返回真
ge如果arg1 >= arg2则返回真

2.6 条件判断

Go 模板语法中的条件判断有以下几种:

{{if pipeline}} T1 {{end}}
{{if pipeline}} T1 {{else}} T0 {{end}}
{{if pipeline}} T1 {{else if pipeline}} T0 {{end}} 

{{if gt .score 60}}
  及格
{{else}}
  不及格
{{end}}

{{if gt .score 90}}
  优秀
{{else if gt .score 60}}
  及格
{{else}}
  不及格
{{end}}

2.7 Range

Go 的模板语法中使用 range 关键字进行遍历,有以下两种写法,其中 pipeline 的值必须是数组、切片、字典或者通道。

{{range $key,$value := .obj}} {{$value}}
{{end}}

如果 pipeline 的值其长度为 0,不会有任何输出

{{$key,$value := .obj}} {{$value}}
{{else}}
pipeline 的值其长度为 0
{{end}}

如果 pipeline 的值其长度为 0,则会执行 T0。

router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "default/index.html", map[string]interface{}{
"hobby": []string{"吃饭", "睡觉", "写代码"}, })
})
{{range $key,$value := .hobby}}
<p>{{$value}}</p> {{end}}

2.8 With

user := UserInfo{
Name: "张三",
Gender: "男",
Age: 18, }
router.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "default/index.html", map[string]interface{}{
"user": user,
}) })

以前要输出数据:

<h4>{{.user.Name}}</h4> <h4>{{.user.Gender}}</h4> <h4>{{.user.Age}}</h4>

现在要输出数据:

{{with .user}} 
<h4>姓名:{{.Name}}</h4> 
<h4>性别:{{.user.Gender}}</h4> 
<h4>年龄:{{.Age}}</h4>
{{end}}

简单理解:相当于 var .=.user

2.9、预定义函数 (了解)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注