Golang Gin Web 框架HTML模版渲染

本页内容

加载HTML并进行渲染

使用 LoadHTMLGlob() 或者 LoadHTMLFiles()加载html文件,这里的区别是LoadHTMLGlob按文件进行匹配,LoadHTMLFiles则需要指定具体文件路径,推荐使用LoadHTMLGlob。


示例

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 文件内容如下,{{ .title }}为设置的展示内容。

示例

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

使用不同目录下名称相同的模板

示例

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")
}


templates/posts/index.tmpl

{{ define "posts/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}

templates/users/index.tmpl


示例

{{ define "users/index.tmpl" }}
<html><h1>
	{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}

自定义模板渲染器

你可以使用自定义的 html 模板渲染


示例

import "html/template"
func main() {
	router := gin.Default()
	html := template.Must(template.ParseFiles("file1", "file2"))
	router.SetHTMLTemplate(html)
	router.Run(":8080")
}

自定义分隔符

你可以使用自定义分隔

示例

r := gin.Default()
	r.Delims("{[{", "}]}")
	r.LoadHTMLGlob("/path/to/templates")

自定义模板功能

这里定义了formatAsDate来对日期进行格式化。

main.go

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")
}


raw.tmpl

Date: {[{.now | formatAsDate}]}

结果:

Date: 2017/07/01

Gin提供的模版功能及HTML渲染已经够日常基本使用,可以用在自己的小项目中,如果企业级项目建议使用前后端分离的方式,可以降低代码维护成本,同时提升前后端协作效率。

此页面最后编辑于2022年9月27日 (星期二) 14:30。