go語言快速入門:模板應用(15)
在go語言中,通過使用http包,可以非常簡單快速地建立一個Web應用。同時使用template包,可以很方便的進行資料替換,如果結合CSS就已經能夠進行簡單的開發了。這篇文章繼續使用簡單的例子來介紹CSS在巢狀template中的使用方式。
例項3
上篇文章通過使用巢狀的template,使得元件式重用變得可能。但是沒有樣式依然顯得較為單調。接下來我們將會在上一篇文章的基礎上嘗試加入簡單的樣式進行頁面的顯示。
例子程式碼
因為只是樣式表的變化,雖然目前的程式極為簡單,但是解耦已經能稍微看到一點。因為程式碼無需作任何變化,仍然是上篇文章的程式碼即可,通過userall.tpl對如下三個部分進行巢狀呼叫。
專案 | 詳細內容 |
---|---|
Header | Person general infor |
Center | Name/Id/Country資訊 |
Footer | Hello, {{.Name}} Welcome to go programming… |
[[email protected] 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)
}
[[email protected] goprj]#
Header部分
使用{{define “”}}方式進行定義,以便使用{{template “”}}方式進行巢狀呼叫,需要注意{{end}}的結尾。格式錯誤可能會帶來無法正常動作的影響。Center和Footer部分也一樣。為了說明和聯絡更加方便,將css部分直接寫到了Header中。
[[email protected] goprj]# cat header.tpl
{{define "header"}}
<html>
<style>
#header{width:1000px;height:30px; background:silver; margin:0px auto;}
#center{width:1000px; height:500px;margin:10px auto 25px;}
#left{width:200px; height:500px;float:left; background:silver;}
#right{width:800px;height:500px;float:left; background:gray;}
#footer{width:1000px;height:100px; background:#DDDDDD ;margin:0px auto;}
</style>
</head>
<body>
<div id="header">
<h3 align=center>Person general infor</h3>
{{end}}
[[email protected] goprj]#
Center部分
[[email protected] goprj]# cat center.tpl
{{define "center"}}
<hr>
</div>
<div id="center">
<div id="left">
<hr>
<ul>
<li>Name: <p>
<li>Id :<p>
<li>Country:
</ul>
<hr>
</div>
<div id="right">
<hr>
<ul>
<li>{{.Name}}<p>
<li>{{.Id}}<p>
<li>{{.Country}}
</ul>
</div>
</div>
{{end}}
[[email protected] goprj]#
Footer部分
[[email protected] goprj]# cat footer.tpl
{{define "footer"}}
<div id="footer">
<h3 align=center>Hello, {{.Name}}, Welcome to go programming...</h3>
</div>
</body>
</html>
{{end}}
[[email protected] goprj]#
巢狀用法
使用{{template “”}}語法進行呼叫,注意有輸出傳遞是需要使用如下格式。userall.tpl未作變化。
[[email protected] goprj]# cat userall.tpl
{{template “header” .}}
{{template “center” .}}
{{template “footer” .}}
[[email protected] goprj]#
執行確認
[root@liumiaocn goprj]# go run basic-web-hello3.go
結果確認
不再是單調地顯示,CSS的結果已經起效。
我們成功地倒入CSS到巢狀的template的應用之中使得原本簡單的頁面變得醜陋無比。然而這並沒有什麼用。
總結
通過匯入CSS到巢狀的template的Web開發之後,至此雖然簡單,使用go語言進行M/V/C的簡單設計和開發,加上Redirect方法基本上就算有了一把簡單的鑰匙,可以自行進行進一步探索了。然而對於想快速進行原型開發但苦於無美工基礎的後端工程師來說,像bootstrap這樣誰做都是一樣難看和好看的框架無疑具有很大吸引力,在後續文章中將會進一步介紹如何使用go+bootstrap進行開發。