理解golang template 的渲染过程
方法1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main
import (
"net/http"
"html/template"
)
func handler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("view.html") //setp 1
t.Execute(w, "Hello World!") //step 2
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/view", handler)
server.ListenAndServe()
}
html 部分内容
1
2
3
4
5
6
7
8
<html>
<head>
<title>First Program</title>
</head>
<body>
{{ . }}
</body>
</html>
方法2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main
import (
"html/template"
"net/http"
)
var tmpl = `<html>
<head>
<title>Hello World!</title>
</head>
<body>
{{ . }}
</body>
</html>
`
func handler(w http.ResponseWriter, r *http.Request) {
t := template.New("main") //name of the template is main
t, _ = t.Parse(tmpl) // parsing of template string
t.Execute(w, "Hello World!")
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/view", handler)
server.ListenAndServe()
}
方法3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main
import (
"net/http"
"html/template"
)
func handler1(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("t1.html", "t2.html")
t.Execute(w, "Asit")
}
func handler2(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("t1.html", "t2.html")
t.ExecuteTemplate(w, "t2.html", "Golang")
}
func main() {
server := http.Server{
Addr: "127.0.0.1:8080",
}
http.HandleFunc("/t1", handler1)
http.HandleFunc("/t2", handler2)
server.ListenAndServe()
}
t1.html
1
2
3
4
5
6
7
8
<html>
<head>
<title>T1 template</title>
</head>
<body>
Hi, My name is {{ . }}.
</body>
</html>
t2.html
1
2
3
4
5
6
7
8
<html>
<head>
<title>T2 template</title>
</head>
<body>
Hi, I am learning {{ . }}.
</body>
</html>
本文网址: https://golangnote.com/topic/182.html 转摘请注明来源