Golang Gin 模板基本使用

发布时间 2023-11-22 18:48:30作者: 看一百次夜空里的深蓝

一, 模板定义,模板变量,条件判断,模板函数,模板命名

  1 {{define "default/index.html"}}
  2 <!DOCTYPE html>
  3 <html lang="en">
  4 
  5 <head>
  6     <meta charset="UTF-8">
  7     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  8     <title>Document</title>
  9     <link rel="stylesheet" href="/static/css/base.css">
 10 </head>
 11 
 12 <body>
 13     <h2>{{.title}}</h2>
 14     <br>
 15     <!-- 定义变量 -->
 16     {{$t := .title}}
 17     <h4>{{$t}}</h4>
 18     <br>
 19     <pre>
 20         eq 如果 arg1 == arg2 则返回真
 21         ne 如果 arg1 != arg2 则返回真
 22         lt 如果 arg1 < arg2 则返回真 
 23         le 如果 arg1 <=arg2 则返回真 
 24         gt 如果 arg1> arg2 则返回真
 25         ge 如果 arg1 >= arg2 则返回真
 26     </pre>
 27     <br>
 28     <h3>条件判断</h3>
 29     <pre>
 30         {{if ge .score 85}}
 31             <p>优秀</p>
 32         {{else if ge .score 60}}
 33             <p>及格</p>
 34         {{else}}
 35             <p>不及格</p>
 36         {{end}}
 37     </pre>
 38     <br>
 39     <h3>range 遍历数据</h3>
 40     <ul>
 41         {{range $key,$value:=.hobby}}
 42         <li>{{$key}}:{{$value}}</li>
 43         {{end}}
 44     </ul>
 45 
 46     <ul>
 47         {{range $key, $value := .testSlice}}
 48         <li>{{$key}}:{{$value}}</li>
 49         {{else}}
 50         <li>数组中没有数据</li>
 51         {{end}}
 52 
 53     </ul>
 54 
 55     <ul>
 56         {{range $key, $value := .news}}
 57         <li>{{$key}}:{{$value.Title}}:{{$value.Content}}</li>
 58         {{end}}
 59     </ul>
 60     <br>
 61     <h3>with 解构结构体</h3>
 62     <p>原来的写法:{{.testWith.Title}}</p>
 63     <p>with写法:
 64 
 65         {{with .testWith}}
 66         {{.Title}}
 67         {{.Content}}
 68         {{end}}
 69     </p>
 70     <br>
 71     <h3>预定义模板函数</h3>
 72     <pre>
 73         执行模板时,函数从两个函数字典中查找,首先时模板函数字典,然后时全局函数字典.
 74         一般不再模板内定义函数,而是使用Funcs方法添加函数到模板里.
 75         and  :  函数返回它的第一个empty参数或者最后一个参数.
 76                 就是说"and x y"  等价于 "if x then y else x" 所有参数都会执行
 77         or   :  返回第一个非empty参数或者最后一个参数.
 78                 亦及"or x y"等价于"if x then x else y" 所有参数都会执行
 79         not  :  返回它的单个参数的bool值的否定
 80         len  :  返回它的参数的整数类型长度
 81         index:  执行结果为第一个参数以剩下的参数为所有/键指向的值
 82                 如"index x 1 2 3"返回 x[1][2][3]的值;每个被索引的主题必须时数组\切片或者字典.
 83         print:  即 fmt.Sprint
 84         printf:  即 fmt.Sprintf
 85         println:  即 fmt.Sprintln
 86         html:   返回与其参数的文本表示形式等效的转义HTML
 87                 这个函数在html/template中不可用
 88         urlquery:以适合嵌入到网址查询中的形式返回其参数的文本表示的转义值.
 89                 这个函数在html/template中不可用
 90         js:     返回与其参数的文本表示形式等效的转义JavaScript
 91         call:   执行结果是调用第一个参数的返回值,该参数必须是函数类型,其余参数作为调用该函数的参数.
 92                 如"call .X.Y 1 2" 等价于"dot.X.Y(1,2)"
 93                 其中Y是函数类型的字段或者字典的值,或者其他类似情况
 94                 call 的第一个参数的执行结果必须是函数类型的值,(和定义的print明显不同)
 95                 该函数类型必须有1到2个返回值,如果有两个则后一个必须是error接口类型
 96                 如果有2个返回值的方法返回的error非nil,模板执行会中断并返回给调用模板执行者该错误
 97         
 98     </pre>
 99     <br>
100     <h3>自定义模板函数</h3>
101     <pre>
102         {{.date}}
103         {{UnixToTime .date}}
104         {{Println .title .msg}}
105     </pre>
106     <br>
107     <h3>模板引用</h3>
108     <pre>
109         注意: 1. public/page_header.html 模板已经定义好了
110               2. 引入的时候注意最后的(.)  将当前页面的数据变量传进去
111         {{template "public/page_header.html" .}}
112     </pre>
113 
114     <br>
115 
116 </body>
117 
118 </html>
119 {{end}}

 

二, 模板加载,自定义模板函数,配置静态web目录

 1 package main
 2 
 3 import (
 4     "fmt"
 5     "net/http"
 6     "text/template"
 7     "time"
 8 
 9     "github.com/gin-gonic/gin"
10 )
11 
12 func main() {
13     TestTemelates()
14 }
15 
16 func UnixToTime(timestamp int) (result string, err error) {
17     fmt.Println(timestamp)
18     t := time.Unix(int64(timestamp), 0)
19     return t.Format("2006-01-02 15:04:05"), nil
20 
21 }
22 
23 func Println(str1, str2 string) string {
24     fmt.Println(str1, str2)
25     return str1 + str2
26 }
27 
28 // 命名模板
29 func TestTemelates() {
30     router := gin.Default()
31 
32     // 自定义模板函数. 必须在加载模板之前SetFuncMap
33     router.SetFuncMap(
34         template.FuncMap{
35             "UnixToTime": UnixToTime,
36             "Println":    Println,
37         })
38 
39     // templates/**/*  代表加载templates下的所有二级目录下的所有模板
40     // templates/**/**/*  代表加载templates下的所有三级目录下的所有模板
41     // 模板分组就是将二级或三级目录的名字写进去
42     router.LoadHTMLGlob("templates/**/*")
43 
44     // 配置静态web目录   第一个参数表示路由   第二个参数表示映射的目录
45     // 这样你就可以通过: localhost:8080/static/css/base.css
46     // 页面引入: <link rel="stylesheet" href="/static/css/base.css">
47     router.Static("/static", "./static")
48 
49     router.GET("/news", func(c *gin.Context) {
50         c.HTML(http.StatusOK, "default/news.html", gin.H{
51             "title": "新闻页面",
52         })
53     })
54 
55     router.GET("/index", func(c *gin.Context) {
56         c.HTML(http.StatusOK, "default/index.html", gin.H{
57             "title": "首页",
58             "score": 85,
59             "hobby": []string{"吃饭", "睡觉", "写代码", "玩游戏"},
60             "news": []interface{}{
61                 &Article{
62                     Title:   "标题1",
63                     Content: "详情1",
64                 },
65                 &Article{
66                     Title:   "标题2",
67                     Content: "详情2",
68                 },
69             },
70             "testSlice": []string{},
71             "testWith": &Article{
72                 Title:   "标题3",
73                 Content: "详情3",
74             },
75             "date": 1700636995,
76             "msg":  "===",
77         })
78     })
79     router.Run("0.0.0.0:8080")
80 }