输出数据 模板语法都包含在{{和}}中间,其中{{.}}中的点表示当前对象。 当我们传入一个结构体对象时,我们可以根据.来访问结构体的对应字段。
{{/* a23 */}}
package main
import (
"fmt"
"html/template"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
type Article struct {
Title string
Content string
}
// 时间戳转化为日期
func UnixToTime(timestamp int) string {
fmt.Print(timestamp)
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 12:22:45")
}
func Println(str1 string, str2 string) string {
fmt.Println(str1, str2)
return str1 + str2
}
func main() {
r := gin.Default()
//配置静态web目录 第一个参数表示路由,第二个表示映射的目录
r.Static("/static", "./static")
//自定义模板函数
r.SetFuncMap(template.FuncMap{
"UnixToTime": UnixToTime,
"Println": Println,
})
// /**/* **表示加载的多层目录结构
r.LoadHTMLGlob("templates/**/*")
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "admin/index.html", gin.H{
"title": "首页",
"score": 99,
})
})
r.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "default/index.html", gin.H{
"title": "首页",
"msg": "adsd",
"score": 99,
"hobby": []string{"吃饭", "睡觉", "写代码"},
"newList": []interface{}{
&Article{
Title: "新闻标题1",
Content: "新闻详情1",
},
&Article{
Title: "新闻标题2",
Content: "新闻详情2",
},
},
"testSlice": []string{},
"news": &Article{
Title: "新闻标题",
Content: "新闻内容",
},
"date": 1629423555,
})
})
r.GET("/default", func(c *gin.Context) {
news := &Article{
Title: "新闻标题",
Content: "新闻内容",
}
c.HTML(http.StatusOK, "default/news.html", gin.H{
"title": "新闻首页",
"news": news,
})
})
r.GET("/news", func(c *gin.Context) {
news := &Article{
Title: "新闻标题",
Content: "新闻内容",
}
c.HTML(http.StatusOK, "admin/news.html", gin.H{
"title": "新闻首页",
"news": news,
})
})
r.Run()
}
{{ define "default/index.html" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/static/css/base.css">
</head>
<body>
<h1>这是默认{{.title}}</h1>
{{$t := .title}}
<br>
<h4>{{$t}}</h4>
{{if gt .score 60}}
<h4>及格</h4>
{{else}}
<h4>不及格</h4>
{{end}}
<ul>
{{range $key,$value := .hobby}}
<li>{{$key}}---{{$value}}</li>
{{end}}
</ul>
<ul>
{{range $key,$value := .newList}}
<li>{{$key}}---{{$value.Title}}---{{$value.Content}}</li>
{{end}}
</ul>
<ul>
{{range $key,$value := .testSlice}}
<li>{{$key}} --- {{$value}}</li>
{{else}}
<li>无数据</li>
{{end}}
</ul>
<br>
{{with .news}}
{{.Title}}
{{.Content}}
{{end}}
{{len .title}}
<br>
<!--自定义模板函数-->
{{.date}}
<br>
{{UnixToTime .date}}
<br>
<br>
{{Println .title .msg}}
</body>
</html>
{{ end }}