<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Title</title></head><body><pre>
尊敬的{{.}}先生/女士
您已经被我公司录取,收到此消息后请您仔细阅读附件中"注意事项"
再次祝您:{{.}}好运
</pre></body></html>
package main
import("net/http""html/template")funcwelcome(w http.ResponseWriter, r *http.Request){
t,_:= template.ParseFiles("view/index.html")
t.Execute(w,"smallming")//此处传递数据}funcmain(){
server := http.Server{Addr:":8090"}
http.HandleFunc("/", welcome)
server.ListenAndServe()}
二. 传递结构体类型数据
结构体的属性首字母必须大写才能被模版访问
在模版中直接使用{{.属性名}}获取结构体的属性
HTML代码如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Title</title></head><body><pre>
当前登录用户信息:<br/>
姓名:{{.Name}}<br/>
年龄:{{.Age}}
</pre></body></html>
go文件代码如下
package main
import("net/http""html/template")//注意:只有首字母大写的属性才能在模版中访问到type User struct{
Name string
Age int}funcwelcome(w http.ResponseWriter, r *http.Request){
t,_:= template.ParseFiles("view/index.html")
t.Execute(w, User{"张三",20})//此处传递数据}funcmain(){
server := http.Server{Addr:":8090"}
http.HandleFunc("/", welcome)
server.ListenAndServe()}
三.向模版传递map类型数据
直接使用{{.key}}获取map中数据
模版中支持连缀写法(不仅仅是map)
go文件代码如下
package main
import("net/http""html/template")//注意:只有首字母大写的属性才能在模版中访问到type User struct{
Name string
Age int}funcwelcome(w http.ResponseWriter, r *http.Request){
t,_:= template.ParseFiles("view/index.html")
m :=make(map[string]interface{})
m["user"]= User{"张三",20}
m["money"]=998
t.Execute(w, m)//此处传递数据}funcmain(){
server := http.Server{Addr:":8090"}
http.HandleFunc("/", welcome)
server.ListenAndServe()}
HTML代码如下,里面使用了连缀写法
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><html><head><title>Title</title></head><body><pre>
当前登录用户信息:<br/>
姓名:{{.user.Name}}<br/>
年龄:{{.user.Age}}<br/>
购物金额:{{.money}}
</pre></body></html>