Go Web【三】模板
简介
来源于B站视频,知识点整理的第三篇
课程视频
如需查看上篇内容请看:
Go-Web基础入门教程(含源码)【第二篇】
Go Web
Web是基于http协议的一个服务,Go语言里面提供了一个完善的net/http包,通过http包可以很方便的就搭建起来一个可以运行的Web服务。
07-1 - 模板:简介
Web模板就是已经被设计好的HTML页面,可以被模板引擎反复的使用产生HTML页面.
Go的标准库提供了 text/template, html/template 两个模板库,大多数的Go-Web框架都使用这两个库作为默认的引擎模板.
Go-Web模板引擎的工作原理
使用模板引擎
- 解析模板源,从而创建一个解析好的模板的struct
- 执行解析好的模板,并传入ResponseWriter和数据
- 会触发模板引擎组合解析好的模板和数据,来产生最终的HTML,并将它传递给ResponseWriter.
案例:使用模板构建HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Template</title>
</head>
<body>
{
{ . }}
</body>
</html>
package main
import (
"net/http"
"text/template"
)
func main() {
server := http.Server{
Addr: "localhost:8888"}
http.HandleFunc("/process", process)
server.ListenAndServe()
}
func process(w http.ResponseWriter, r *http.Request) {
// ParseFiles 返回一个模板template和一个err
// 传入文件路径是一个相对路径
t, _ := template.ParseFiles("teml.html")
t.Execute(w, "Hello,World!")
}
07-2 - 模板:解析与执行
ParseFiles
- 解析模板文件并创建一个解析好的struct,后续可以被执行
- ParseFiles函数是Template struct 上 ParseFiles 方法的简便调用
- 调用 ParseFiles后,会创建一个新的模板,模板的名字是文件名
- New函数
- ParseFiles的参数的数量可变,但仍只返回一个模板
- 当解析多个文件的时候,第一个文件作为返回的模板,其余的作为map,供后续的执行使用.
package main
import (
"fmt"
"net/http"
"text/template"
)
func main() {
// t := template.New("tmpl.html")
// t, _ := t.ParseFiles("tmpl.html")
// 上面两句和下面一句效果等价
t, _ := template.ParseFiles("tmpl.html")
fmt.Println(t)
}
ParseGlob
- 使用模式匹配来解析特定的文件
// 按照指定的匹配模式进行解析
func ParseGlob(pattern string) (*Template, error) {
// 内部调用了 parseGlob 方法
return parseGlob(nil, pattern)
}
//
func parseGlob(t *Template, pattern string) (*Template, error) {
// 返回所有符合匹配模式的文件名称
filenames, err := filepath.Glob(pattern)
if err != nil {
return nil, err
}
if len(filenames) == 0 {
return nil, fmt.Errorf("template: pattern matches no files: %#q", pattern)
}
// 回到了上面提到的 parseFiles
return parseFiles(t, readFileOS, filenames...)
}
Parse
- 可以解析字符串模板,其他方式最终都会调用 Parse
Lookup
- 通过模板名称来寻找模板,如果没有找到就返回
nil
Must
- 可以包裹一个函数,返回一个模板的指针和一个错误
- 如果错误不为
nil
, 就会panic
执行模板
package main
import (
"net/http"
"text/template"
)
func main() {
server := http.Server{
Addr: "localhost:8888"}
http.HandleFunc("/process", process)
server.ListenAndServe()
}
func process(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("t1.html")
t.Execute(w, "Hello,World!")
ts, _ := template.ParseFiles("t1.html", "t2.html")
ts.ExecuteTemplate(w, "t2.html", "Hello,World!")
}
07-2 - Demo:解析与执行
本节将完成一个解析与执行模板的综合性案例:
本节的目录格式如下:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
)
func loadTemplate() *template.Template {
result := template.New("templates")
template.Must(result.ParseGlob("templates/*.html"))
// result, err := template.ParseGlob("templates/*.html")
// template.Must(result, err)
return result
}
func main() {
templates := loadTemplate()
http.HandleFunc(