HTML 渲染

使用 LoadHTMLGlob() 或者 LoadHTMLFiles()

  1. func main() {
  2. router := gin.Default()
  3. router.LoadHTMLGlob("templates/*")
  4. //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  5. router.GET("/index", func(c *gin.Context) {
  6. c.HTML(http.StatusOK, "index.tmpl", gin.H{
  7. "title": "Main website",
  8. })
  9. })
  10. router.Run(":8080")
  11. }

templates/index.tmpl

  1. <html>
  2. <h1>
  3. {{ .title }}
  4. </h1>
  5. </html>

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

  1. func main() {
  2. router := gin.Default()
  3. router.LoadHTMLGlob("templates/**/*")
  4. router.GET("/posts/index", func(c *gin.Context) {
  5. c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
  6. "title": "Posts",
  7. })
  8. })
  9. router.GET("/users/index", func(c *gin.Context) {
  10. c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
  11. "title": "Users",
  12. })
  13. })
  14. router.Run(":8080")
  15. }

templates/posts/index.tmpl

  1. {{ define "posts/index.tmpl" }}
  2. <html><h1>
  3. {{ .title }}
  4. </h1>
  5. <p>Using posts/index.tmpl</p>
  6. </html>
  7. {{ end }}

templates/users/index.tmpl

  1. {{ define "users/index.tmpl" }}
  2. <html><h1>
  3. {{ .title }}
  4. </h1>
  5. <p>Using users/index.tmpl</p>
  6. </html>
  7. {{ end }}

自定义模板渲染器

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

  1. import "html/template"
  2. func main() {
  3. router := gin.Default()
  4. html := template.Must(template.ParseFiles("file1", "file2"))
  5. router.SetHTMLTemplate(html)
  6. router.Run(":8080")
  7. }

自定义分隔符

你可以使用自定义分隔

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

自定义模板功能

查看详细示例代码

main.go

  1. import (
  2. "fmt"
  3. "html/template"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func formatAsDate(t time.Time) string {
  9. year, month, day := t.Date()
  10. return fmt.Sprintf("%d/%02d/%02d", year, month, day)
  11. }
  12. func main() {
  13. router := gin.Default()
  14. router.Delims("{[{", "}]}")
  15. router.SetFuncMap(template.FuncMap{
  16. "formatAsDate": formatAsDate,
  17. })
  18. router.LoadHTMLFiles("./testdata/template/raw.tmpl")
  19. router.GET("/raw", func(c *gin.Context) {
  20. c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
  21. "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
  22. })
  23. })
  24. router.Run(":8080")
  25. }

raw.tmpl

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

结果:

  1. Date: 2017/07/01

Last modified 07.03.2020 : add blog dir (#115) (f46734b)