当前位置:首页 > 文章列表 > Golang > Go教程 > Go语言模板渲染HTML入门指南

Go语言模板渲染HTML入门指南

2025-12-25 08:00:31 0浏览 收藏

大家好,今天本人给大家带来文章《Go语言模板渲染HTML教程》,文中内容主要涉及到,如果你对Golang方面的知识点感兴趣,那就请各位朋友继续看下去吧~希望能真正帮到你们,谢谢!

Golang使用html/template包渲染HTML,支持数据安全嵌入与XSS防护。1. 可通过Parse解析内联模板并传入结构体数据渲染;2. 常用ParseFiles加载外部HTML文件,便于维护;3. 支持模板复用,利用define和block实现布局继承;4. 自动HTML转义防止注入,可信内容可用template.HTML绕过转义。

如何在Golang中使用模板渲染HTML

在Golang中使用模板渲染HTML,主要依赖标准库中的 html/template 包。它不仅能安全地将数据嵌入HTML,还能防止XSS攻击。下面介绍如何实际操作。

1. 基本HTML模板渲染

你可以定义一个简单的HTML模板字符串,然后用数据填充并输出到HTTP响应中。

package main

import (
    "html/template"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    t := template.Must(template.New("example").Parse(`
        <html>
        <body>
            <h1>Hello, {{.Name}}!</h1>
        </body>
        </html>
    `))

    data := struct{ Name string }{Name: "Alice"}
    t.Execute(w, data)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

访问 http://localhost:8080 就能看到渲染后的页面。注意:{{.Name}} 是模板语法,用来插入结构体字段。

2. 使用外部HTML文件

更常见的是把HTML模板放在独立文件中,便于维护。

创建文件 templates/index.html

<!DOCTYPE html>
<html>
<head><title>Golang Template</title></head>
<body>
    <h2>Welcome, {{.Username}}</h2>
    <p>You have {{.MessageCount}} new messages.</p>
</body>
</html>

Go代码加载并渲染该文件:

func handler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("templates/index.html")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    data := struct {
        Username      string
        MessageCount  int
    }{
        Username:     "Bob",
        MessageCount: 5,
    }

    t.Execute(w, data)
}

3. 模板复用:布局与块

对于多个页面共用头部和底部,可以使用模板继承。

创建 templates/layout.html

<html>
<head><title>{{block "title" .}}Default Title{{end}}</title></head>
<body>
    <header><h1>My Website</h1></header>
    <main>
        {{block "content" .}}<p>No content.</p>{{end}}
    </main>
</body>
</html>

子模板 templates/home.html

{{define "title"}}Home Page{{end}}
{{define "content"}}
    <h2>Home</h2>
    <p>Welcome to the home page.</p>
{{end}}

Go代码:

func homeHandler(w http.ResponseWriter, r *http.Request) {
    tmpl := template.Must(template.ParseFiles(
        "templates/layout.html",
        "templates/home.html",
    ))
    tmpl.ExecuteTemplate(w, "layout", nil)
}

这样就能实现页面结构统一,内容按需替换。

4. 安全与转义说明

html/template 会自动对输出进行HTML转义,防止脚本注入。例如,如果数据包含