Contents
10.18. template模板¶
Printf也可以做到输出格式化,当然,对于简单的例子来说足够了,但是我们有时候还是需要复杂的
输出格式,甚至需要将格式化代码分离开来。这时,可以使用text/template和html/template。
Go 官方库提供了两个模板库:
text/templatehtml/template。
这两个库类似,当需要输出html格式的代码时需要使用 html/template。
10.18.1. text/template¶
所谓模板引擎,则将模板和数据进行渲染的输出格式化后的字符程序。对于Go,执行这个流程大概需要 三步。
·创建模板对象
·加载模板
·执行渲染模板
其中最后一步就是把加载的字符和数据进行格式化。
package main
import (
"log"
"os"
"text/template"
)
const templ = `
{{range .}}----------------------------------------
Name: {{.Name}}
Price: {{.Price |printf "%4s"}}
{{end}}
`
var report = template.Must(template.New("report").Parse(templ))
type Book struct {
Name string
Price float64
}
func main() {
Data := []Book{{"《三国演义》", 19.7}, {"《水浒传》", 20.2}, {"" +
"西游记", 40}, {"《红楼梦》", 50}}
if err := report.Execute(os.Stdout, Data); err !=nil{
log.Fatal(err)
}
}
如果把模板的内容存在一个文本文件里tmp.txt
{{range .}}----------------------------------------
Name: {{.Name}}
Price: {{.Price |printf "%4s"}}
{{end}}
处理文本文件示例:
ParseFiles接受一个字符串,字符串的内容是一个模板文件的路径。
package main
import (
"log"
"os"
"text/template"
)
var report = template.Must(template.ParseFiles("D:\\go_studay\\go_path\\src\\github.com\\medallion42\\template01\\sample02\\tmp.txt"))
type Book struct {
Name string
Price float64
}
func main() {
Data := []Book{{"《三国演义》", 19.7}, {"《水浒传》", 20.2}, {"" +
"西游记", 40}, {"《红楼梦》", 50}}
if err := report.Execute(os.Stdout, Data); err !=nil{
log.Fatal(err)
}
}
ParseGlob是用正则的方式匹配多个文件
写成template.ParseGlob(“*.txt”) 即可。
var report = template.Must(template.ParseFiles("tmp.txt")
10.18.2. html/template¶
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ . }}
</body>
</html>
sample.go
package main
import (
"html/template"
"net/http"
)
func tHandler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("D:\\go_studay\\go_path\\src\\github.com\\medallion42\\template01\\sample03\\index.html")
t.Execute(w, "Hello World!")
}
func main() {
http.HandleFunc("/", tHandler)
http.ListenAndServe(":8080", nil)
}
运行程序,在浏览器打开:http://localhost:8080/会看到页面显示Hello
World!