在go语言中,通过使用http包,可以非常简单快速地创建一个Web应用。同时使用template包,可以很方便的进行数据替换,如果结合CSS就已经能够进行简单的开发了。这篇文章继续使用简单的例子来介绍template的嵌套使用方式。
实例2
随着单页面应用程序的推广,出现了很多不同的框架,可以快速的实现复杂的开发。其实使用template也是一种常见的方法,比如可以将能够重复利用的部分做成template,然后反复利用。这个例子中我们将会将其分成Header/Center/Footer三部分,然后组合成我们要显示的内容。详细三部分进行如下划分:
项目 | 详细内容 |
---|---|
Header | Person general infor |
Center | Name/Id/Country信息 |
Footer | Hello, {{.Name}} Welcome to go programming… |
例子代码
这个例子中,使用userall.tpl嵌套调用了Header/Center/Footer三个模板文件,注意ParseFiles的文件顺序。另外ExecuteTemplate的方式可以对某一特定模板进行处理,在实际的时候也有很多应用场景。
[root@liumiaocn goprj]# cat basic-web-hello3.go
package main
import "fmt"
import "net/http"
import "html/template"
func Hello(response http.ResponseWriter, request *http.Request) {
type person struct {
Id int
Name string
Country string
}
liumiaocn := person{Id: 1001, Name: "liumiaocn", Country: "China"}
tmpl, err := template.ParseFiles("./userall.tpl","./header.tpl","./center.tpl","./footer.tpl")
if err != nil {
fmt.Println("Error happened..")
}
tmpl.Execute(response,liumiaocn)
}
func main() {
http.HandleFunc("/", Hello)
http.ListenAndServe(":8080", nil)
}
[root@liumiaocn goprj]#
Header部分
使用{{define “”}}方式进行定义,以便使用{{template “”}}方式进行嵌套调用,需要注意{{end}}的结尾。格式错误可能会带来无法正常动作的影响。Center和Footer部分也一样。
[root@liumiaocn goprj]# cat header.tpl
{{define "header"}}
<html>
<head>
<title>Personal information</title>
</head>
<body style="text-align:center">
<h3>Person general infor</h3>
{{end}}
[root@liumiaocn goprj]#
Center部分
[root@liumiaocn goprj]# cat center.tpl
{{define "center"}}
<hr>
<ul>
<li>Name: {{.Name}}<p>
<li>Id: {{.Id}} <p>
<li>Country: {{.Country}}
</ul>
{{end}}
[root@liumiaocn goprj]#
Footer部分
[root@liumiaocn goprj]# cat footer.tpl
{{define "footer"}}
<hr>
<h3>Hello, {{.Name}} Welcome to go programming...</h3>
</body>
</html>
{{end}}
[root@liumiaocn goprj]#
嵌套用法
使用{{template “”}}语法进行调用,注意有输出传递是需要使用如下格式。
[root@liumiaocn goprj]# cat userall.tpl
{{template “header” .}}
{{template “center” .}}
{{template “footer” .}}
[root@liumiaocn goprj]#
结果执行
[root@liumiaocn goprj]# go run basic-web-hello3.go
结果确认
总结
这篇文章中将template的使用方式继续改进,使用嵌套的方式使得数据模型/表现/控制的框架自由搭建更为方便。在后续文章中,将会进一步将CSS的使用方式加入进来。