模版
Go模板使用
在Go语言中,我们使用template包来进行模版处理,使用类似Parse,ParseFile,Execute等方法来从文件或字符串中加载模版
- Parse可以直接测试一个字符串,不需要额外的文件,ParseFile需要额外的文件
字段操作
Go语言的模板通过{{}}来包含需要再渲染时被替换的字段,{{.}}表示当前的对象,相当于java当中的this关键字,如果要访问当前对象的字段通过{{.FieldName}},但是需要注意的是:这个字段必须是导出的,也就是首字母必须是大写的,否则会报错
type Student struct {
Name string
}
func main() {
t1 := template.New("student demo")
t1,_ = t1.Parse(`hello {{.Name}}`)
stu := Student{"zhangsan"}
t1.Execute(os.Stdout,stu)
}
输出嵌套字段内容
上面的例子是针对一个对象的字段输出,如果字段里面还有对象,如何来循环输出这些内容,我们可以使用{{with ...}}...{{end}}和{{range ...}}{end}来进行数据输出
- {{range}} 这个和Go语法里面的range类似,循环操作数据
- {{with}}操作是指当前对象的值,类似于上下文
type Student struct {
Name string
}
type Classes struct {
ClassName string
Ages []int
Stus []*Student
}
func main() {
stu1 := Student{"Jim"}
stu2 := Student{"Tom"}
class := Classes{ClassName:"三年二班",Ages:[]int{18,19,20},Stus:[]*Student{&stu,&stu1,&stu2}}
t2 := template.New("class demo")
t2,_ = t2.Parse(`这是 {{.ClassName}}
群体年龄包含有
{{range .Ages}}
{{.}}
{{end}}
包含有学生:
{{with .Stus}}
{{range .}}
{{.Name}}
{{end}}
{{end}}
`)
t2.Execute(os.Stdout,class)
}
条件处理
Go模板中如果需要进行条件判断,那么我们可以使用if-else语句来处理,如果if中有内容则认为是true,否则则认为是false
func main() {
tEmpty := template.New("test")
//Must 用于检测模板是否正确,例如大括号是否匹配
tEmpty = template.Must(tEmpty.Parse("空的 if demo : {{if ``}} 不会输出{{end}}\n"))
tEmpty.Execute(os.Stdout,nil)
tWithValue := template.New("test")
tWithValue = template.Must(tWithValue.Parse("不为空的 if demo:{{if `abc`}}我有内容我输出{{end}}\n"))
tWithValue.Execute(os.Stdout,nil)
tIFELSE := template.New("test")
tIFELSE = template.Must(tIFELSE.Parse("is-else demo:{{if `true`}} if部分 {{else}} else部分{{end}}\n"))
tIFELSE.Execute(os.Stdout,nil)
}
模版变量
在模版使用过程中需要定义一些局部变量,可以在一些操作中申明局部变量,例如with,range,if中使用一些变量,这个变量的作用域是{{end}}之前,Go语言通过申明的局部变量格式如下所示:
$variable := pipeline
例如
//模版变量
func main() {
t1 := template.New("test")
t1,_ = t1.Parse( `{{with $x := "output" | printf "%s\n"}}{{$x}}{{end}}`)
t1.Execute(os.Stdout,nil)
t2 := template.New("test")
t2,_ = t2.Parse( `{{with $x := "output"}}{{printf "%q\n" $x}}{{end}}`)
t2.Execute(os.Stdout,nil)
t3 := template.New("test")
t3,_ = t3.Parse( `{{with $x := "output"}}{{$x | printf "%q"}}{{end}}`)
t3.Execute(os.Stdout,nil)
}
网友评论