理解golang template 的渲染过程
🕗 Tue, 08 Aug 2017 by GolangNote
理解golang template 的渲染过程
方法1:
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>
<head>
<title>First Program</title>
</head>
<body>
{{ . }}
</body>
</html>
方法2:
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:
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>
<head>
<title>T1 template</title>
</head>
<body>
Hi, My name is {{ . }}.
</body>
</html>
t2.html
<html>
<head>
<title>T2 template</title>
</head>
<body>
Hi, I am learning {{ . }}.
</body>
</html>
本文网址: https://golangnote.com/topic/182.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Relative Articles
Recent Go Articles
- Golang 把cookie 字符串解析为cookie 结构
- Golang 计算字符串中包含某个或某些字符集的个数
- 使用Golang 对文件增删写读操作备忘
- Go Modules 使用备忘
- 使用Golang 简单删除图片exif 信息
- 谷歌翻译的 golang 库推荐
- Go 1.13.2 与1.13.3 紧急更新
- golang 人脸检测识别库
- Go build 错误 “stackcheck redeclared in this block previous declaration”的解决方法
- Golang phantomjs 动态代理实现
- Golang chrome debug protocol 库推荐
- Golang 随机打乱数组/Slice
- Golang sync.WaitGroup 的 Wait 超时处理
- Golang实现简单的Socks5代理
- Golang 用snappy + Base64 简单压缩加密进行网络传输
- Golang http IPv4/IPv6 服务
- golang 全角半角相互转换
- 在自己的网站部署TLS 1.3
- Golang 实现/打印菜单树
- Golang telegram 机器人小试
Top Go Articles
- golang 人脸检测识别库
- Golang 时区时差处理方式
- golang 把上传文件转为byte
- GoLang Map key 排序输出的例子
- go 获取硬盘的可用空间的方法
- golang 实现python 的dict.keys() dict.values() 函数
- golang 原生xml 转json
- Golang slice 和 map 的查询性能比较
- Caddy、 SSLDocker、Nginx 性能比较及使用体验
- Golang io.ReadCloser 和[]byte 相互转化的方法
- Golang 减小gc 压力、避免内存泄漏小tips
- Golang telegram 机器人小试
- GoLang 遍历目录的不同方法
- Golang 字符串毫秒转时间格式
- iris websocket 自定义信息结构
- golang 正确获取绝对路径的方法
- Golang 随机打乱数组/Slice
- 在go web 应用里避免全局变量
- 关于Golang msgpack 和 json 性能的简单比较
- Golang 合并byte 的性能比较