1、使用 LoadHTMLGlob() 或者 LoadHTMLFiles()

template1.go:

package main

import "net/http"
import "github.com/gin-gonic/gin"

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>

 

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

template2.go:

package main

import "net/http"
import "github.com/gin-gonic/gin"

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

 

3、自定义模板渲染器

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

template3.go:

package main

import (
	"html/template"
	"net/http"

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

func main() {
	router := gin.Default()
	html := template.Must(template.ParseFiles("templates/file1.tmpl", "templates/file2.tmpl"))
	router.SetHTMLTemplate(html)
	router.GET("/file1", func(c *gin.Context) {
		c.HTML(http.StatusOK, "file1.tmpl", gin.H{
			"title": "Posts",
		})
	})
	router.GET("/file2", func(c *gin.Context) {
		c.HTML(http.StatusOK, "file2.tmpl", gin.H{
			"title": "Users",
		})
	})
	router.Run(":8080")
}

templates/file1.tmpl:

<html>
<h1>
	{{ .title }}
</h1>
<p>Using file1</p>
</html>

templates/file2.tmpl:

<html>
<h1>
	{{ .title }}
</h1>
<p>Using file2</p>
</html>

 

4、自定义模板功能

在模板中使用自定义函数 formatAsDate

template4.go:

package main

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("./templates/raw.tmpl")

	router.GET("/raw", func(c *gin.Context) {
		c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
			"now": time.Date(2020, 2, 23, 0, 0, 0, 0, time.UTC),
		})
	})

	router.Run(":8080")
}

templates/raw.tmpl:

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

允许后访问 http://127.0.0.1:8080/raw 输出:

Date: 2020/02/23