小白教程
所有教程
关于
Search
172.70.130.199
172.70.130.199
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Golang Gin Web 框架HTML模版渲染”的源代码
本页内容
上一节:
Golang_Gin_Web_框架快速入门
下一节:
Golang_Gin_Web_框架路由
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
[[分类:Golang Gin Web 框架教程]] == 加载HTML并进行渲染 == 使用 LoadHTMLGlob() 或者 LoadHTMLFiles()加载html文件,这里的区别是LoadHTMLGlob按文件进行匹配,LoadHTMLFiles则需要指定具体文件路径,推荐使用LoadHTMLGlob。 <sample title="" desc="" > 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") } </sample> templates/index.tmpl 文件内容如下,'''<nowiki>{{ .title }}</nowiki>'''为设置的展示内容。 <sample title="" desc=""> <html> <h1> {{ .title }} </h1> </html> </sample> == 使用不同目录下名称相同的模板 == <sample title="" desc="" > func main() { router := gin.Default() router.LoadHTMLGlob("templates/**/*") router.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ "title": "Posts", }) }) router.GET("/users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.tmpl", gin.H{ "title": "Users", }) }) router.Run(":8080") } </sample> <sample title="templates/posts/index.tmpl " desc=""> {{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }} </sample> templates/users/index.tmpl <sample title="" desc=""> {{ define "users/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using users/index.tmpl</p> </html> {{ end }} </sample> == 自定义模板渲染器 == 你可以使用自定义的 html 模板渲染 <sample title="" desc=""> import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") } </sample> === 自定义分隔符 === 你可以使用自定义分隔 <sample title="" desc=""> r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates") </sample> === 自定义模板功能 === 这里定义了formatAsDate来对日期进行格式化。 <sample title="main.go" desc="" > import ( "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") } </sample> <sample title="raw.tmpl" desc="" > Date: {[{.now | formatAsDate}]} </sample> 结果: Date: 2017/07/01 Gin提供的模版功能及HTML渲染已经够日常基本使用,可以用在自己的小项目中,如果企业级项目建议使用前后端分离的方式,可以降低代码维护成本,同时提升前后端协作效率。
返回至“
Golang Gin Web 框架HTML模版渲染
”。
上一节:
Golang_Gin_Web_框架快速入门
下一节:
Golang_Gin_Web_框架路由