Gin框架Gin渲染


Gin框架Gin渲染

一、HTML渲染

package main

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

func main() {
	r := gin.Default()

	// 解析模板
	r.LoadHTMLFiles("./templates/index.tmpl")

	r.GET("/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.tmpl", gin.H{
			// H is a shortcut for map[string]interface{}
			//type H map[string]interface{}
			// 渲染模板
			"title": "gin渲染模板",
		})

	})

	r.Run(":9999")

}




    
    
    
    users/index


{{.title}}



二、HTML渲染多个文件

我们首先定义一个存放模板文件的templates文件夹,然后在其内部按照业务分别定义一个posts文件夹和一个users文件夹。 posts/index.html文件的内容如下:

{{define "posts/index.tmpl"}}
    
    

    
        
        
        
        posts/index
    
    
    {{.title}}
    
    
{{end}}

users/index.html文件的内容如下:

{{define "users/index.tmpl"}}



    
    
    
    users/index


{{.title}}


{{end}}

Gin框架中使用LoadHTMLGlob()多个模板文件或者LoadHTMLFiles()单个文件方法进行HTML模板渲染。

package main

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

func main() {
	r := gin.Default()

	// 解析模板
	r.LoadHTMLGlob("./templates/**/*")
    
    // 请求
	r.GET("/posts/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
			// H is a shortcut for map[string]interface{}
			//type H map[string]interface{}
			// 渲染模板
			"title": "posts/index.tmpl",
		})

	})
    
	r.GET("/users/index", func(c *gin.Context) {

		c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
			// H is a shortcut for map[string]interface{}
			//type H map[string]interface{}
			// 渲染模板
			"title": "users/index.tmpl",
		})

	})

	r.Run(":9999") // 启动server

}

三、自定义模板函数

定义一个不转义相应内容的safe模板函数如下:

package main

import (
	"github.com/gin-gonic/gin"
	"html/template"
	"net/http"
)

func main() {
	r := gin.Default()
	// 自定义函数在解析模板之前定义
	
	r.SetFuncMap(template.FuncMap{
		"safe": func(str string) template.HTML {
			return template.HTML(str)
		},
	})
	
	
	// 解析模板
	r.LoadHTMLGlob("./templates/**/*")
	r.GET("/custom/func/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "customFunc.tmpl", gin.H{
			// H is a shortcut for map[string]interface{}
			//type H map[string]interface{}
			// 渲染模板
			"title": "自定义函数",
		})

	})
	r.Run(":9999") // 启动server
}

index.tmpl中使用定义好的safe模板函数:




    修改模板引擎的标识符


{{ .title | safe }}