七叶笔记 » golang编程 » Go Web 框架 Gin 学习3 – 模板渲染多级目录与模板传参

Go Web 框架 Gin 学习3 – 模板渲染多级目录与模板传参

1、LoadHTMLGlob多级目录

 engine.LoadHTMLGlob("template1/**/*")  
 func (engine *Engine) LoadHTMLGlob(pattern string)  

LoadHTMLGlob有1个参数,可以使用 通配符 ,”template1/*”表示template1目录下的所有文件

当模板目录template1结构如下:

 └─template1
    ├─admin
    │      index. HTML 
    │
    ├─index
    │      index.html
    │
    └─users
            index.html  

那么需要注意的是,每个index.html都要有{{ define “…”}}……{{end}},将html包裹起来,

可以理解为给index.html起个别名,用于区分不同文件夹下相同名字文件的别名。

因为c.HTML(http.StatusOK, “index2”, nil )中的index2就是所定义的别名

define “…”:中的…就是别名

……:是html内容

2、模板传参

 func admin(c *gin.Context) {
c.HTML(http.StatusOK, "admin_index", gin.H{
"user": "admin",
"pass": "123456",
})
}  

其中gin.H是map[string]interface{}的别名,

c.HTML有3个参数,

 func (c *Context) HTML(code int, name string, obj interface{})  

HTML renders the HTTP template specified by its file name. It also updates the HTTP code and sets the Content-Type as “text/html”.

作用是渲染模板文件,将响应头的Content-Type设置为 “text/html”

code int:响应码,可以写成http.StatusOK这样的常量,也可以直接写成200,因为http.StatusOK的常量值就是200,当然有可以写成相匹配的响应码,这里只是以正常响应的200举例

name string:这里就是模板名,默认是文件名,如果使用{{define “…”}}……{{end}}进行了定义,那么就可以写成别名。

obj interface{}:这里就是传入模板的对象,类型是空接口类型,也就是说,可以传入任意类型的值,模板都是可以接受的,在func admin(c *gin.Context)示例中,传入了gin.H这样的map类型,那么就可以在模板文件中进行使用。

示例代码:

 package main

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

func main() {
   engine := gin.Default()
   engine.LoadHTMLGlob("template1/**/*")
   engine.GET("/admin", admin)
   engine.GET("/index", index)
   engine.GET("/users", users)
   _ = engine.Run(" 127.0.0.1 :80")
}

func admin(c *gin.Context) {
   c.HTML(http.StatusOK, "admin_index", gin.H{
      "user": "admin",
      "pass": "123456",
   })
}
func index(c *gin.Context) {
   c.HTML(http.StatusOK, "index_index", nil)
}

func users(c *gin.Context) {
   c.HTML(http.StatusOK, "users_index", nil)
}
  

模板文件:

执行结果:

相关文章