您的位置:首页 > 编程语言 > Go语言

go语言快速入门:模板应用(15)

2017-02-06 21:56 681 查看
在go语言中,通过使用http包,可以非常简单快速地创建一个Web应用。同时使用template包,可以很方便的进行数据替换,如果结合CSS就已经能够进行简单的开发了。这篇文章继续使用简单的例子来介绍CSS在嵌套template中的使用方式。

实例3

上篇文章通过使用嵌套的template,使得组件式重用变得可能。但是没有样式依然显得较为单调。接下来我们将会在上一篇文章的基础上尝试加入简单的样式进行页面的显示。

例子代码

因为只是样式表的变化,虽然目前的程序极为简单,但是解耦已经能稍微看到一点。因为代码无需作任何变化,仍然是上篇文章的代码即可,通过userall.tpl对如下三个部分进行嵌套调用。

项目详细内容
HeaderPerson general infor
CenterName/Id/Country信息
FooterHello, {{.Name}} Welcome to go programming…
[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部分也一样。为了说明和联系更加方便,将css部分直接写到了Header中。

[root@liumiaocn 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}}
[root@liumiaocn goprj]#


Center部分

[root@liumiaocn 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}}
[root@liumiaocn goprj]#


Footer部分

[root@liumiaocn goprj]# cat footer.tpl
{{define "footer"}}
<div id="footer">
<h3 align=center>Hello, {{.Name}}, Welcome to go programming...</h3>
</div>

</body>
</html>
{{end}}
[root@liumiaocn goprj]#


嵌套用法

使用{{template “”}}语法进行调用,注意有输出传递是需要使用如下格式。userall.tpl未作变化。

[root@liumiaocn goprj]# cat userall.tpl

{{template “header” .}}

{{template “center” .}}

{{template “footer” .}}

[root@liumiaocn goprj]#

执行确认

[root@liumiaocn goprj]# go run basic-web-hello3.go


结果确认

不再是单调地显示,CSS的结果已经起效。



我们成功地倒入CSS到嵌套的template的应用之中使得原本简单的页面变得丑陋无比。然而这并没有什么用。

总结

通过导入CSS到嵌套的template的Web开发之后,至此虽然简单,使用go语言进行M/V/C的简单设计和开发,加上Redirect方法基本上就算有了一把简单的钥匙,可以自行进行进一步探索了。然而对于想快速进行原型开发但苦于无美工基础的后端工程师来说,像bootstrap这样谁做都是一样难看和好看的框架无疑具有很大吸引力,在后续文章中将会进一步介绍如何使用go+bootstrap进行开发。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  go语言