boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

如何用Golang渲染HTML模板 详解template包的用法


avatar
作者 2025年8月25日 12

在 go 语言中,html/template 包用于安全地渲染 html 模板,防止 xss 攻击,其核心用法包括定义模板、解析文件、嵌套复用、自定义函数及结合 http 服务输出动态内容,必须使用导出字段并注意自动转义机制,最终通过 execute 或 executetemplate 方法将数据注入模板并完整输出 html 内容。

如何用Golang渲染HTML模板 详解template包的用法

在 Go 语言中,

html/template

包是处理 HTML 模板渲染的核心工具。它不仅安全(自动转义防止 XSS 攻击),而且功能强大,适合构建动态网页内容。下面详细介绍如何使用

template

包来渲染 HTML 页面。


一、基本用法:定义模板并渲染数据

html/template

的核心是将结构化数据注入到 HTML 模板中,生成最终的 HTML 输出。

package main  import (     "html/template"     "log"     "os" )  type User struct {     Name  string     Email string }  func main() {     // 定义模板字符串     const tmpl = `<h1>Hello, {{.Name}}!</h1><p>Email: {{.Email}}</p>`      // 解析模板     t, err := template.New("user").Parse(tmpl)     if err != nil {         log.Fatal(err)     }      // 准备数据     user := User{Name: "Alice", Email: "alice@example.com"}      // 渲染模板到标准输出     err = t.Execute(os.Stdout, user)     if err != nil {         log.Fatal(err)     } }

输出结果:

立即学习go语言免费学习笔记(深入)”;

<h1>Hello, Alice!</h1><p>Email: alice@example.com</p>

注意:使用 html/template 而不是 text/template,因为前者会对输出自动进行 HTML 转义,防止 XSS。


二、加载外部 HTML 文件模板

通常模板会写在

.html

文件中,便于维护。

假设有一个

templates/index.html

<!DOCTYPE html> <html> <head><title>User Info</title></head> <body>     <h1>Welcome, {{.Name}}!</h1>     <p>Your email is: {{.Email}}</p> </body> </html>

Go 代码加载并渲染:

t, err := template.ParseFiles("templates/index.html") if err != nil {     log.Fatal(err) } user := User{Name: "Bob", Email: "bob@example.com"} t.Execute(os.Stdout, user)

也可以一次加载多个模板文件:

template.ParseFiles("header.html", "footer.html", "index.html")

三、使用

template.Must

简化错误处理

template.Must

是一个辅助函数,用于包装

Parse

ParseFiles

,如果解析失败会直接 panic。

t := template.Must(template.ParseFiles("templates/index.html")) t.Execute(os.Stdout, user)

适用于开发阶段或确定模板文件一定存在的情况。


四、模板语法详解

1. 数据引用

  • {{.}}

    :表示当前上下文的数据

  • {{.FieldName}}

    :访问结构体字段(必须是导出字段,首字母大写)

  • {{.Field.Nested}}

    :支持嵌套结构

type Profile struct {     User  User     Age   int     Hobbies []string }

模板中:

<p>Age: {{.Age}}</p> <p>Hobbies: {{range .Hobbies}}<span>{{.}}</span>{{end}}</p>

2. 控制结构

  • if 判断

    {{if .Email}}   <p>Email: {{.Email}}</p> {{else}}   <p>No email provided.</p> {{end}}
  • range 遍历

    <ul> {{range .Hobbies}}   <li>{{.}}</li> {{end}} </ul>
  • with:切换上下文

    {{with .User}}   <h2>{{.Name}}</h2> {{end}}

3. 变量定义(以

$

开头)

{{ $email := .Email }} <p>Contact: {{$email}}</p>

可以在

range

中避免变量覆盖时使用。


五、模板嵌套与复用:

template

可以定义多个命名模板,并在主模板中嵌套使用。

例如

layout.html

{{define "header"}} <html><head><title>{{.Title}}</title></head><body> {{end}}  {{define "footer"}} </body></html> {{end}}
page.html

{{template "header" .}} <h1>{{.Content}}</h1> {{template "footer" .}}

Go 代码:

t := template.Must(template.ParseFiles("layout.html", "page.html")) data := map[string]string{     "Title":   "My Page",     "Content": "Hello World", } t.ExecuteTemplate(os.Stdout, "page.html", data)
ExecuteTemplate

可以指定执行某个命名模板。


六、自定义函数:

FuncMap

你可以向模板中注入自定义函数,比如格式化时间、转大写等。

funcMap := template.FuncMap{     "upper": strings.ToUpper,     "formatDate": func(t time.Time) string {         return t.Format("2006-01-02")     }, }  t := template.New("demo").Funcs(funcMap) t, err := t.Parse("Name: {{.Name | upper}}")

使用管道

|

调用函数。


七、常见陷阱与注意事项

  • 字段必须可导出:模板只能访问结构体中首字母大写的字段。
  • 自动转义:HTML、JS、URL 等内容会被自动转义。若要输出原始 HTML,使用
    template.HTML

    类型:

    type Data struct {     Content template.HTML } data := Data{Content: template.HTML("<b>Bold text</b>")}

    否则

    <b>

    会被转义成

    <b>

  • 模板缓存:生产环境建议预解析模板,避免每次请求都解析。
  • 错误处理:模板执行错误(如字段不存在)会返回错误,需检查
    Execute

    返回值。


八、结合 HTTP 服务使用

在 Web 应用中,通常配合

net/http

使用:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {     t := template.Must(template.ParseFiles("templates/index.html"))     user := User{Name: "Alice", Email: "alice@example.com"}     t.Execute(w, user) }) http.ListenAndServe(":8080", nil)

基本上就这些核心用法。掌握

html/template

包后,你可以在不引入前端框架的情况下,用 Go 构建简单的动态网页应用。关键是理解数据传递、模板语法和安全转义机制。



评论(已关闭)

评论已关闭