Go語言中html/template模塊詳細功能介紹與示例代碼
Go語言的 html/template
模塊是專門用于生成安全 HTML 輸出的模板引擎,支持自動轉(zhuǎn)義以防止 XSS 攻擊。以下是該模塊的核心方法及用法示例:
1. 基礎(chǔ)模板解析與渲染
template.Parse 和 template.Execute
解析模板字符串并渲染數(shù)據(jù)。
package main import ( "html/template" "os" ) func main() { // 定義模板字符串 tmplStr := `<h1>{{.Title}}</h1><p>{{.Content}}</p>` // 解析模板 tmpl, err := template.New("page").Parse(tmplStr) if err != nil { panic(err) } // 定義數(shù)據(jù) data := struct { Title string Content string }{ Title: "歡迎頁面", Content: "這是安全渲染的內(nèi)容!", } // 渲染并輸出到標(biāo)準(zhǔn)輸出 err = tmpl.Execute(os.Stdout, data) if err != nil { panic(err) } }
輸出結(jié)果:
<h1>歡迎頁面</h1><p>這是安全渲染的內(nèi)容!</p>
2. 從文件加載模板
template.ParseFiles
從多個文件加載模板,支持模板繼承和嵌套。
// 文件: templates/header.html {{ define "header" }}<header>{{.SiteName}}</header>{{ end }} // 文件: templates/page.html {{ define "page" }} <!DOCTYPE html> <html> {{ template "header" . }} <body> <h1>{{.Title}}</h1> </body> </html> {{ end }}
func main() { // 解析多個模板文件 tmpl, err := template.ParseFiles( "templates/header.html", "templates/page.html", ) if err != nil { panic(err) } // 渲染數(shù)據(jù) data := struct { SiteName string Title string }{ SiteName: "我的網(wǎng)站", Title: "主頁", } // 指定使用 "page" 模板渲染 err = tmpl.ExecuteTemplate(os.Stdout, "page", data) }
輸出結(jié)果:
<!DOCTYPE html> <html> <header>我的網(wǎng)站</header> <body> <h1>主頁</h1> </body> </html>
3. 自動轉(zhuǎn)義與安全內(nèi)容
自動轉(zhuǎn)義 XSS 內(nèi)容
默認(rèn)情況下,所有變量內(nèi)容會被轉(zhuǎn)義。
data := struct { UserInput string }{ UserInput: "<script>alert('xss')</script>", } tmplStr := `<div>{{.UserInput}}</div>` tmpl, _ := template.New("test").Parse(tmplStr) tmpl.Execute(os.Stdout, data)
輸出結(jié)果:
<div><script>alert('xss')</script></div>
信任原始 HTML
使用 template.HTML
類型標(biāo)記安全內(nèi)容。
data := struct { SafeContent template.HTML }{ SafeContent: template.HTML("<b>加粗文本</b>"), } tmplStr := `<div>{{.SafeContent}}</div>` tmpl, _ := template.New("test").Parse(tmplStr) tmpl.Execute(os.Stdout, data)
輸出結(jié)果:
<div><b>加粗文本</b></div>
4. 自定義模板函數(shù)
Funcs 與 template.FuncMap
注冊自定義函數(shù)到模板中。
func main() { // 定義自定義函數(shù) funcMap := template.FuncMap{ "safeHTML": func(s string) template.HTML { return template.HTML(s) }, } // 創(chuàng)建模板并注冊函數(shù) tmplStr := `<div>{{. | safeHTML}}</div>` tmpl := template.New("test").Funcs(funcMap) tmpl, _ = tmpl.Parse(tmplStr) // 渲染數(shù)據(jù) tmpl.Execute(os.Stdout, "<em>斜體文本</em>") }
輸出結(jié)果:
<div><em>斜體文本</em></div>
5. 條件判斷與循環(huán)
if 和 range 語法
在模板中實現(xiàn)邏輯控制。
data := struct { ShowHeader bool Items []string }{ ShowHeader: true, Items: []string{"Go", "Python", "Java"}, } tmplStr := ` {{ if .ShowHeader }}<h1>列表</h1>{{ end }} <ul> {{ range .Items }} <li>{{ . }}</li> {{ end }} </ul> ` tmpl, _ := template.New("list").Parse(tmplStr) tmpl.Execute(os.Stdout, data)
輸出結(jié)果:
<h1>列表</h1> <ul> <li>Go</li> <li>Python</li> <li>Java</li> </ul>
6. 嵌套模板與塊定義
define 和 template 指令
復(fù)用模板片段。
// 定義基礎(chǔ)模板 tmplStr := ` {{ define "layout" }} <!DOCTYPE html> <html> <head>{{ template "title" }}</head> <body>{{ template "content" . }}</body> </html> {{ end }} {{ define "title" }}<title>默認(rèn)標(biāo)題</title>{{ end }} {{ define "content" }}<p>默認(rèn)內(nèi)容</p>{{ end }} ` // 覆蓋部分塊 customTmplStr := ` {{ define "content" }}<h1>{{.Message}}</h1>{{ end }} ` // 解析模板 tmpl, _ := template.New("base").Parse(tmplStr) tmpl, _ = tmpl.Parse(customTmplStr) // 渲染數(shù)據(jù) data := struct{ Message string }{Message: "自定義內(nèi)容"} tmpl.ExecuteTemplate(os.Stdout, "layout", data)
輸出結(jié)果:
<!DOCTYPE html> <html> <head><title>默認(rèn)標(biāo)題</title></head> <body><h1>自定義內(nèi)容</h1></body> </html>
總結(jié)
- 安全性:自動轉(zhuǎn)義 HTML 特殊字符,防止 XSS 攻擊。
- 核心方法:
Parse
,ParseFiles
,Execute
,Funcs
。 - 高級功能:
- 嵌套模板(
define
和template
)。 - 條件與循環(huán)(
if
、range
)。 - 自定義函數(shù)(
Funcs
)。
- 嵌套模板(
- 適用場景:動態(tài)生成安全 HTML 頁面,如 Web 應(yīng)用的后端渲染。
到此這篇關(guān)于Go語言中html/template模塊詳細功能介紹與示例代碼的文章就介紹到這了,更多相關(guān)Go語言html/template模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用Gin框架返回JSON、XML和HTML數(shù)據(jù)
Gin是一個高性能的Go語言Web框架,它不僅提供了簡潔的API,還支持快速的路由和中間件處理,在Web開發(fā)中,返回JSON、XML和HTML數(shù)據(jù)是非常常見的需求,本文將介紹如何使用Gin框架來返回這三種類型的數(shù)據(jù),需要的朋友可以參考下2024-08-08golang語言實現(xiàn)的文件上傳與文件下載功能示例
這篇文章主要介紹了golang語言實現(xiàn)的文件上傳與文件下載功能,結(jié)合實例形式分析了Go語言實現(xiàn)的文件傳輸相關(guān)操作技巧,需要的朋友可以參考下2020-02-02Golang 基礎(chǔ)之函數(shù)使用(匿名遞歸閉包)實例詳解
這篇文章主要為大家介紹了Golang 基礎(chǔ)之函數(shù)使用(匿名遞歸閉包)實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-10-10