- package main
-
- import (
- "github.com/gin-gonic/gin"
- _ "net/http"
- "testgin01/myfunc"
- )
-
-
-
- func main() {
- r := gin.Default()
- //r.LoadHTMLFiles("/temp/hello01.html")
- r.LoadHTMLGlob("temp/**/*") // **/代表一个文件级
- //指定cSS文件
- r.Static("/s","style") //css文件需要使用相对路径
- //r.StaticFS("/s",http.Dir("static")) 另外一种引入CSS路径的映射方式
- //r.GET("/demo02",myfunc.Hello ) //定义路径下页面,通配,页面需要加
- //r.GET("/demo02",myfunc.Hello2 )
- r.GET("/demo02",myfunc.Hello07)
- // define end标签
-
-
-
- r.Run()
-
- }
函数单独写一个页面
- package myfunc
-
- import "github.com/gin-gonic/gin"
-
- func Hello(context *gin.Context) {
- //context.String(300,"这是我的第一个gin")
- name := "你好我是golang" //将要渲染的字符串传入,在页面上使用上下文获取{{.}}
-
- context.HTML(200,"demo02/hello02.html",name)
- //加载的html路径
- }
-
- type Student struct {
- Name string
- Age int64
- }
- func Hello2(context *gin.Context) {
- s := Student{
- Name: "goland" ,
- Age: 2018,
-
- }
- context.HTML(300,"demo02/hello02.html",s)
- }
-
- func Hello3(context *gin.Context) {
- var arr [3]int
- arr[0] = 10
- arr[1] = 20
- arr[2] = 30
- context.HTML(400,"demo02/hello02.html",arr)
- }
- func Hello5(context *gin.Context){
-
- var a map[string]int = make(map[string]int,3)
- a ["lili"] = 18
- a["菲菲"] =12
- a["毛毛"] =3
-
- context.HTML(200,"demo02/hello02.html",a)
-
- }
- func Hello6(context *gin.Context) {
- var a map[string]Student = make(map[string]Student,3)
- a["No1"]= Student{
- Name:"毛毛",
- Age: 2,
-
- }
- a["No2"]= Student{
- Name:"菲菲",
- Age:21,
- }
- context.HTML(200,"demo02/hello02.html",a)
- }
-
- func Hello07(context *gin.Context) {
- slice := []int{1,2,3,4,5}
-
- context.HTML(200,"demo02/hello02.html",slice)
- }
-
网页样式写一个页面
- {{ define "demo02/hello02.html"}}
- "en">
- "UTF-8">
-
Title - "stylesheet" href="/s/css/mycss.css">
-
- 这是hello02的页面
- 这部分我想要红色
- {{/* 这部分我想要红色 */}}
- {{/*{{.Name}}
*/}} - {{/*{{.Age}}*/}}
- {{/*{{range .}}*/}}
- {{/*第一个点代表的是传入的数组的上下文,第二个点代表的变量的数组的上下文*/}}
- {{/*{{.}}*/}}
- {{/*{{end}}*/}}
-
- {{/*第二种方式,带下标*/}}
- {{/*{{range $i,$v := .}}*/}}
- {{/*{{$i}}*/}}
- {{/*{{$v}}*/}}
- {{/*{{end}}*/}}
- {{/*获取map中的内容,通过key获取value*/}}
- {{/*{{.lili}}*/}}
- {{/*{{.毛毛}}*/}}
- {{/*.是上下文,key得到value*/}}
- {{/*{{.No1.Name}}*/}}
- {{/*{{.No2.Age}}*/}}
- {{range .}}
- {{.}}
- {{end}}
- {{range $i ,$v := .}}
- {{$i}}
- {{$v}}
- {{end}}
-
-
-
-
-
- {{end}}
这是hello02的页面 这部分我想要红色 1 2 3 4 5 0 1 1 2 2 3 3 4 4 5
运行结果,数组和切片可以通过{{rang ,}} {{.}}{{end}} 来实现遍历
其他如 map,struct可以使用键值对