使用LoadHTMLGlob() or LoadHTMLFiles()加载模板文件路径
router.LoadHTMLGlob(“templates/") 全局加载templates/下一级模板文件
router.LoadHTMLGlob("templates/**/”) 全局加载templates/*/下二级模板文件
router.LoadHTMLFiles()加载指定路径模板文件
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") //router.LoadHTMLFiles("templates/front/index.html", "templates/web/index.html") router.GET("/front/index", func(c *gin.Context) { c.HTML(http.StatusOK, "front/index.html", gin.H{ "title": "首页", "desc":"front", }) }) router.GET("/web/index", func(c *gin.Context) { c.HTML(http.StatusOK, "web/index.html", gin.H{ "title": "后台", "desc":"web", }) }) router.Run(":8080") }
{{define “模板名称”}} {{end}} 定义在不同目录中使用同名模板
{{ template “需引用模板” .}} 添加需要引用的模板,后面的点.表示将数据传入模板
{{.title}}表示获取变量title的值
front/index.html
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14{{define "front/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{.title}}</title> </head> <body> <h1>我是网址首页</h1> {{ template "common.html" .}} </body> </html> {{end}}
web/index.html
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14{{define "web/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{.title}}</title> </head> <body> <h1>我是网址后台</h1> {{ template "common.html" .}} </body> </html> {{end}}
common.html
复制代码
1
2
3
4<div> <span style="color: blue">我是网页公共部分 - {{.desc}}</span> </div>
自定义模板渲染
你可以使用自己的html渲染
复制代码
1
2
3
4
5
6
7
8
9import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") }
自定义分隔符
使用自己喜欢的符号来获取模板变量数据
复制代码
1
2
3
4r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates")
自定义模板函数
使用自定义的函数来处理传入到模板里的数据
main.go
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31import ( "fmt" "html/template" "net/http" "time" "github.com/gin-gonic/gin" ) func formatAsDate(t time.Time) string { year, month, day := t.Date() return fmt.Sprintf("%d/%02d/%02d", year, month, day) } func main() { router := gin.Default() router.Delims("{[{", "}]}") router.SetFuncMap(template.FuncMap{ "formatAsDate": formatAsDate, }) router.LoadHTMLFiles("./testdata/template/raw.tmpl") router.GET("/raw", func(c *gin.Context) { c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), }) }) router.Run(":8080") }
raw.tmpl
复制代码
1
2Date: {[{.now | formatAsDate}]}
Result
复制代码
1
2Date: 2017/07/01
more use detail : https://gin-gonic.com/docs/examples/
最后
以上就是舒适路人最近收集整理的关于gin -html rendering的全部内容,更多相关gin内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复