各种类型数据渲染
一、字符串渲染
u.Ctx.WriteString(“hello world”)
二、模板渲染
1.结构体数据渲染
结构体:
type Student struct{
Name string
Age int
Gender string
}
赋值:
c.Data["student"] = Student{Name:"知了课堂",Age:18,Gender:"男"}
前端使用:
学生姓名:{{.student.Name}}
学生年龄:{{.student.Age}}
学生性别:{{.student.Gender}}
注意:结构体中的字段要在其他地方使用,比如首字母大写
2.数组数据渲染
lista := [5]int{1,2,3,4,5}
c.Data["arr"] = lista
前端:
第一种:
{{range $i,$v := .arr}}
{{$i}}
{{$v}}
{{end}
第二种:
{{range .arr}}
{{.}}
{{end}}
3.结构体数组渲染
结构体:
type student struct {
Name string
Age int
Gender string
}
赋值:
arr_struct := [3]student{{Name:"hl",Age:18,Gender:"男"},{Name:"hallen",Age:19,Gender:"男"},{Name:"hallen1",Age:191,Gender:"男"}}
c.Data["arr_struct"] = arr_struct
前端获取:先循环数组,在获取结构体变量,注意是大写
{{range $v := .arr_struct}}
{{$v.Name}}
{{$v.Age}}
{{$v.Gender}}
{{range .books}}
{{.Name}}
{{.Author}}
{{end}}
4.map数据渲染
//teacher :=map[string]string{"name":"张三","age":"18"}
teacher :=make(map[string]string)
teacher["name"]="老王"
teacher["age"]="30"
c.Data["teacher"] = teacher
前端:
取出key对应的值
{{.teacher.name}}
{{.teacher.age}}
取出所有的key和value:
{{range $k,$v := .teacher}}
{{$k}}
{{$v}}
{{end}}
5.结构体和map组合渲染
结构体:
type student struct {
Name string
Age int
Gender string
}
赋值:
mapa := make(map[int]student)
mapa[101] = student{Name:"张三1",Age:181,Gender:"男"}
mapa[102] = student{Name:"张三2",Age:182,Gender:"男"}
mapa[103] = student{Name:"张三3",Age:183,Gender:"男"}
c.Data["hero_map"] = mapa
前端获取:先循环map,在获取结构体变量,注意是大写
{{range $v :=.hero_map}}
{{$v.Name}}
{{end}}
6.切片数据渲染
listb := []int{1,2,3,4,5,6,7}
c.Data["list_b"] = listb
前端:只有一个值的时候默认是切片的元素,而不是角标
{{range $v := .list_b}}
{{$v}}
{{end}}