登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  Golang >  Go教程

Go语言模板渲染HTML入门教程

时间:2026-04-16 14:05:36 234浏览 收藏

本文深入浅出地介绍了Go语言中使用标准库html/template安全高效渲染HTML的完整实践:从内联模板解析与结构体数据绑定,到分离维护的外部HTML文件加载;从基于define/block的布局继承实现模板复用,到自动HTML转义机制对XSS攻击的天然防护,以及在严格控制下安全绕过转义的技巧。无论你是构建轻量Web服务、生成动态邮件,还是打造可维护的前端页面,这套简洁而严谨的模板方案都能帮你兼顾开发效率与生产安全——掌握这些核心用法,就能在Go生态中稳健输出可信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(`
        
        
            

Hello, {{.Name}}!

`)) 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



Golang Template

    

Welcome, {{.Username}}

You have {{.MessageCount}} new messages.

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


{{block "title" .}}Default Title{{end}}

    

My Website

{{block "content" .}}

No content.

{{end}}

子模板 templates/home.html

{{define "title"}}Home Page{{end}}
{{define "content"}}
    

Home

Welcome to the home page.

{{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转义,防止脚本注入。例如,如果数据包含