goctl 技术系列 - Go 模板入门
简介
在 Web 开发中,动态网页是至关重要的一部分,它能够根据用户的请求和数据动态地生成内容。Go 语言通过其强大的标准库提供了一种称为 text/template
的模板引擎,用于构建动态网页和生成文本输出。本文将介绍如何使用 text/template
包来创建和渲染动态网页。
本文为开篇示例,展示简单的模板驱动及其效果。即使对 text/template
语法不熟悉,也无需担心,后续篇幅会逐步讲解。
什么是 text/template
?
text/template
是 Go 语言标准库中的一部分,它允许我们定义模板,并通过填充数据来生成输出。这种模板引擎设计简单而高效,适用于生成 HTML 网页、配置文件、邮件文本等内容。
准备工作
在开始之前,请确保已安装 Go 语言开发环境,并熟悉基本的 Go 语法和数据结构。
创建你的第一个模板
让我们从一个简单的 HTML 模板开始。首先,新建工程 demo
,进入 demo
目录,在该目录下创建一个名为 index.html
的模板文件,并添加以下内容:
<!-- created by go-zero 知识星球 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模板示例</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 20px;
}
th, td {
border: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
</style>
</head>
<body>
<h2>数据展示列表(使用 text/template 模板驱动)</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
{{range .}}
<tr>
<td>{{.ID}}</td>
<td>{{.Name}}</td>
<td>{{.Age}}</td>
<td>{{.City}}</td>
</tr>
{{end}}
</tbody>
</table>
</body>
</html>
在模板文件 index.html
中,使用了 {{.ID}}
、{{.Name}}
、{{.Age}}
和 {{.City}}
这样的占位符,它们将在数据渲染时被实际的值替代。在未进行数据渲染前,访问 index.html
文件,得到的视图如下:
在 Go 程序中使用模板
现在,让我们在 Go 程序中加载并渲染这个模板。创建一个名为 main.go
的文件,并添加以下代码:
// created by go-zero 知识星球
package main
import (
"bytes"
_ "embed"
"fmt"
"net/http"
"text/template"
)
//go:embed index.html
var indexTmpl string
type Person struct {
ID int // ID 对应 html 模板中的{{.ID}}占位符变量,严格区分大小写,其他几个字段类似
Name string
Age int
City string
}
func main() {
// 注册路由 index,用于渲染 web 页面
http.HandleFunc("/index", func(writer http.ResponseWriter, request *http.Request) {
// 模拟数据
people := []Person{
{1, "John Doe", 30, "New York"},
{2, "Jane Smith", 25, "Los Angeles"},
{3, "Mary Johnson", 35, "Chicago"},
}
// 解析模板
t := template.Must(template.New("webpage").Parse(indexTmpl))
// 创建一个缓冲区,用于存储渲染后的结果
renderWriter := bytes.NewBuffer(nil)
// 执行模板渲染
err := t.Execute(renderWriter, people)
if err != nil { // 渲染失败,返回错误信息
writer.WriteHeader(http.StatusBadRequest)
_, _ = writer.Write([]byte(err.Error()))
return
}
// 渲染成功,返回渲染后的结果
writer.WriteHeader(http.StatusOK)
writer.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = writer.Write(renderWriter.Bytes())
})
fmt.Println("Started success, you can visit http://localhost:8080/index to see the result.")
err := http.ListenAndServe(":8080", nil) // 启动服务
if err != nil {
fmt.Println("Starting server error:", err)
}
}
在这个示例中,people
是一个包含 Person
结构体的切片,每个 Person
结构体代表表格中的一行数据。模板中使用了 range .
来迭代 people
切片,并为每个 Person
结构体生成一行 <tr>
。
运行并查看效果
在命令行中使用 go run main.go
运行程序。访问 http://localhost:8080/index 页面,可以看到输出是一个包含三行数据的 HTML 表格,每行显示一个人的信息。
这种方式使得 HTML 生成更加动态和可扩展,适用于需要根据数据动态生成表格内容的场景。
总结
通过本文,我们探讨了如何利用 Go 语言的 text/template
包构建动态网页。从定义简单的 HTML 模板开始,到在 Go 程序中加载并渲染模板,展示了如何通过模板驱动的方式动态生成内容丰富的网页。
text/template
包提供了强大而灵活的工具,使开发人员能够通过简单的占位符在模板中插入数据,并根据需求动态生成 HTML 输出。这种方法不仅提升了网页内容的个性化和交互性,同时也增强了代码的可维护性和扩展性。