GolangNote

Golang笔记

理解golang template 的渲染过程

Permalink

理解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>

本文网址: https://golangnote.com/topic/182.html 转摘请注明来源

Related articles

Golang telegram 机器人小试

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。...

Golang 数据库 Bolt 碎片整理

Bolt 是一个优秀、纯 Go 实现、支持 ACID 事务的嵌入式 Key/Value 数据库。但在使用过程中会有很多空间碎片。一般数据库占用的空间是元数据空间的 1.5~4 倍。Bolt 没有内置的压缩功能,需要手动压缩。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms