文本模板template
374字约1分钟
2025-02-03
假设有一个名为 template.tpl 的模板文件,内容如下:
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
<h1>你好, {{.Name}}!</h1>
<p>你的年龄是 {{.Age}}.</p>
<p>你来自 {{.Country}}.</p>
</body>
</html>
对于格式化后的模板内容,打印输出
package main
import (
"os"
"text/template"
)
// 定义一个结构体用于填充模板数据
type Person struct {
Name string
Age int
Country string
Title string
}
func main() {
// 打开模板文件
file, err := os.Open("/tmp/template.tpl")
if err != nil {
panic(err)
}
defer file.Close()
// 解析模板文件
t, err := template.ParseFiles("/tmp/template.tpl")
if err != nil {
panic(err)
}
// 定义要填充的数据
person := Person{
Name: "阿哲",
Age: 18,
Country: "中国",
Title: "hello",
}
// 使用 os.Stdout 作为输出,将数据填充到模板中并输出到标准输出
err = t.Execute(os.Stdout, person)
if err != nil {
panic(err)
}
}
对于格式化后的模板内容,保存到文件
package main
import (
"os"
"text/template"
)
// 定义一个结构体用于填充模板数据
type Person struct {
Name string
Age int
Country string
Title string
}
func main() {
// 打开或创建一个名为 template.html 的文件,如果文件不存在则创建,如果存在则截断文件
file, err := os.Create("/tmp/template.html")
if err != nil {
panic(err)
}
defer file.Close()
// 解析模板文件
t, err := template.ParseFiles("/tmp/template.tpl")
if err != nil {
panic(err)
}
// 定义要填充的数据
person := Person{
Name: "张三",
Age: 28,
Country: "中国",
Title: "欢迎来到我的地盘",
}
// 使用文件作为输出,将数据填充到模板中并写入到文件
err = t.Execute(file, person)
if err != nil {
panic(err)
}
}