gin架构下实现页面的数据调用

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()

	}

函数单独写一个页面

Go 复制代码
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)
}

网页样式写一个页面

Go 复制代码
{{ define  "demo02/hello02.html"}}
<!DOCTYPE html>
<html lang="en">
<link>
    <meta charset="UTF-8">
    <title>Title</title>
    <link  rel="stylesheet" href="/s/css/mycss.css">
 <body>
 这是hello02的页面
 <span> 这部分我想要红色</span>
 {{/*<span  style="color: red">   这部分我想要红色 </span>*/}}
 {{/*{{.Name}}<br>*/}}
 {{/*{{.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}}




</body>

</html>
{{end}}
Go 复制代码
这是hello02的页面 这部分我想要红色 1 2 3 4 5 0 1 1 2 2 3 3 4 4 5

运行结果,数组和切片可以通过{{rang ,}} {{.}}{{end}} 来实现遍历

其他如 map,struct可以使用键值对

相关推荐
小于负无穷4 天前
Go 中 Gin 框架的使用指南
开发语言·后端·golang·gin
落雨便归尘5 天前
go语言后端开发学习(七)——如何在gin框架中集成限流中间件
后端·学习·中间件·golang·gin
knoci8 天前
【Go】-基于Gin和GORM的小清单项目
开发语言·golang·gin
Boo_T8 天前
三十三、Gin的中间件
开发语言·后端·golang·gin
Boo_T8 天前
三十七、Gin完成登陆功能
开发语言·后端·golang·gin
揽月随风醉9 天前
Gin-封装自动路由
gin
Boo_T9 天前
三十五、Gin注册功能实战
开发语言·后端·golang·gin
好奇的菜鸟9 天前
Gin 自带日志系统:深入理解与自定义
gin
Boo_T9 天前
三十六、Gin注册功能-检查账号是否存在
开发语言·后端·golang·gin
knoci9 天前
【Go】-Gin框架
开发语言·后端·学习·golang·gin