使用golang的标准库搭建网站--2.模板解析
发布时间:2020-12-16 18:36:13 所属栏目:大数据 来源:网络整理
导读:模板的解析 既然是搭建网站, fmt.F printf (w, "Hello world,this is my first page!" ) 这种方式肯定就不能用了,得解析模板才行。 模板解析用到的包是”html/template”,先导包,然后改写Index函数: //先导入html/template包 import "html/template" fu
模板的解析既然是搭建网站, fmt.Fprintf(w,"Hello world,this is my first page!")
这种方式肯定就不能用了,得解析模板才行。 //先导入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>
这样就能正常解析模板啦 未完待续……. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |