GolangNote

Golang笔记

理解golang template 的渲染过程

Permalink

理解golang template 的渲染过程

理解golang template 的渲染过程

方法1

Go: 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 部分内容

HTML: 模版文件
1
2
3
4
5
6
7
8
<html>
<head>
    <title>First Program</title>
</head>
<body>
    {{ . }}
</body>
</html>

方法2

Go: template 的渲染方法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

Go: template 的渲染方法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

HTML: 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

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>

Related articles

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

Write a Comment to "理解golang template 的渲染过程"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 1ms