HTML 渲染

    templates/index.tmpl

    1. <h1>
    2. {{ .title }}
    3. </h1>
    4. </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")

    templates/posts/index.tmpl

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

    raw.tmpl

      结果: