您的位置 首页 golang

Golang Web编程,示例学习,模板的继承、渲染、多模板的使用

main.go

 package main

import (
	"net/http"
	"text/template"
)

func Index(w http.ResponseWriter, r *http.Request) {
	//func ParseFiles(filenames ...string) (*Template, error)
	//ParseFiles从"index.html"中解析模板。
	//如果发生错误,解析停止,返回的*Template为nil。
	//当解析多个文件时,如果文件分布在不同目录中,且具有相同名字的,将以最后一个文件为主。
	files, _ := template.ParseFiles("header.html", "footer.html", "index.html")
	//func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error
	//ExecuteTemplate方法负责渲染模板,可以指定主要的模板,并将该模板写入到http.ResponseWriter中。
	//ExecuteTemplate方法有3个参数
	//第一个参数:设置响应http.ResponseWriter
	//第二个参数:指定显示的模板文件
	//第三个参数:传递到模板的内容
	//如果在执行模板或写入输出时发生错误,执行会停止。
	v := map[string]interface{}{
		"title":"这里是显示title内容",
		"id":1,
		"name":"张无忌",
		"age":18,
		"header":"传递到header.html的内容",
		"footer":"传递到footer.html的内容",
	}
	_ = files.ExecuteTemplate(w, "index.html", v)
}
func main() {
	http.HandleFunc("/", Index)
	_ = http.ListenAndServe("", nil)
}
  

index.html

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{.title}}</title>
</head>
<body>
<pre>
    这里是index.html
    {{.id}}
    {{.name}}
    {{.age}}
</pre>
{{/*加载header.html模板*/}}
{{template "header.html" .}}
{{template "footer.html" .}}
</body>
</html>  

footer.html

 <h1>这里是footer.html</h1>
<h3>{{.footer}}</h3>  

header.html

 <h1>这里是header.html</h1>
<h3>{{.header}}</h3>  

main_test.go

 package main

import (
   "io/ioutil"
   "net/http"
   "net/http/httptest"
   "testing"
)

func TestIndex(t *testing.T) {
   //初始化测试服务器
   handler := http.HandlerFunc(Index)
   app := httptest.NewServer(handler)
   defer app.Close()
   //测试代码
   //发送http.Get请求,获取请求结果response
   response, _ := http.Get(app.URL + "/index")
   //关闭response.Body
   defer response.Body.Close()
   //读取response.Body内容,返回字节集内容
   bytes, _ := ioutil.ReadAll(response.Body)
   //将返回的字节集内容通过string()转换成字符串,并显示到日志当中
   t.Log(string(bytes))
}
  

执行结果

执行结果

文章来源:智云一二三科技

文章标题:Golang Web编程,示例学习,模板的继承、渲染、多模板的使用

文章地址:https://www.zhihuclub.com/97323.shtml

关于作者: 智云科技

热门文章

网站地图