模板的解析
既然是搭建网站,
fmt.Fprintf(w,"Hello world,this is my first page!")
这种方式肯定就不能用了,得解析模板才行。
模板解析用到的包是”html/template”,先导包,然后改写Index函数:
//先导入html/template包
import "html/template"
func Index(w http.ResponseWriter,r *http.Request) {
//解析指定模板文件index.html
t,_ := template.ParseFiles("index.html")
//输出到浏览器
t.Execute(w,nil)
}
在准备一个html文件,如下:
<HTML>
<head>
<title>
这是一个测试文件
</title>
</head>
<body>
<p>
Hello world,this is my first page!
</p>
</body>
</HTML>
运行一下,得到和上面一样的结果。
接着向模板中插入数据,很容易:
func Index(w http.ResponseWriter,r *http.Request) {
//用于保存数据的map
data := make(map[string]string)
t,_ := template.ParseFiles("index.html")
data["Name"] = "BCL"
t.Execute(w,data)
}
在HTML文件中插入一个新的标签:
<p> Hello,{{.Name}} </p>
这样就能正常解析模板啦
下面我们就简单的了解一下go语言的模板的语法
未完待续…….
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。