Gin模板语法

115 阅读2分钟

Gin模板语法


前提提醒

  • 由于有了前面template包的基础,所以该笔记不再过多详细分析

Gin框架启动服务器

  • 语法:

    • r:=gin.Default()//获取一个Engine变量
    • r.Get("网站路径",handleFunc...)//Get请求
    • r.Run(addr ...string)//启动服务器

模板解析

  • 语法:

    • r.LoadHTMLFiles(...filename)
    • r.LoadHTMLGlob("./ginTemplates/**/*")(正则表达式解析所有文件,"**"代表表示任意层级子目录, *代表任意文件

模板渲染

  • 语法:

    • r.Get("网站路径",handleFunc...)

    • 例子

       r.GET("/posts/index", func(c *gin.Context) {
               c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
                   "title": "欢迎来到POSTS世界",
                   "url":   "<a href = 'http://localhost:9000/users/index'>USER世界</a>",
               })
           })
      

遇到不同目录下相同的文件如何加载和渲染

  • 方法: 在tmpl模板中用define关键字定义名字,再解析

  • 例子:

     {{/*通过定义名字区分不同目录下相同文件名的文件渲染和解析*/}}
     {{define "posts/index.tmpl"}}//<----主要是这里
     <!DOCTYPE html>
     <html lang="en">
     <head>
         <meta charset="UTF-8">
         {{/*加载css静态文件需要在头部连接*/}}
         <link  rel="stylesheet" href="/xxx/index.css">
         <title>Gin模板渲染</title>
     </head>
     <body>
     <script src = "/xxx/index.js"></script>
     <h1>{{.title}}</h1>
     <p>{{.url | safe}}</p>
     <p>{{hello}}</p>
     </body>
     </html>
     {{end}}
    

自定义函数

  • 语法:

    • r.SetFuncMap(funcMap template.FuncMap)//其内部包装的是 template.FuncMap,所以原理一样
  • 注意:需要在模板解析前添加自定义函数

  • 例子

         r.SetFuncMap(template.FuncMap{
             "safe": func(str string) template.HTML {
                 return template.HTML(str) //强转
             },
             "hello": func() string {
                 return "hello"
             },
         })
    
  • 用法:

    • 像是safe这种可以传参的,可以通过"|"符号应用到某个字符中

    • 例子:

       //tmpl
       <p>{{.url | safe}}</p>
       ​
       //后端
       r.GET("/posts/index", func(c *gin.Context) {
               c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
                   "title": "欢迎来到POSTS世界",
                   "url":   "<a href = 'http://localhost:9000/users/index'>USER世界</a>",
               })
           })
      
      • 这里的url会被转义为template.HTML类型输出到网页中
    • hello这种只是传文字的可以直接使用

    • 例子:

       //tmpl
       <p>{{hello}}</p>
       ​
       //后端
       r.GET("/posts/index", func(c *gin.Context) {
               c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
                   "title": "欢迎来到POSTS世界",
                   "url":   "<a href = 'http://localhost:9000/users/index'>USER世界</a>",
               })
           })
      

加载静态文件

  • 语法: r.Static(参数1,参数2)

    •  第一个参数"/xxx"表示在请求URL中使用的访问前缀。
       第二个参数:为实际文件所在目录的路径*/
      
  • 使用

    • css中演示(其他基本一致)

    • 例子:

       <link  rel="stylesheet" href="/xxx/index.css">
       ​
       //后端
       r.Static("/xxx", "./statics")
      
      • 这里的/xxx是请求URL中使用的访问前缀
      • ./statics为文件目录的路径
      • /index.css为目标文件的路径