Golang教程Go语言中的模板引擎使用指南

我在学习Go语言的模板引擎时遇到了一些困惑。想请教各位:Go语言的标准库中html/template和text/template有什么区别?在实际项目中应该如何选择?模板中的管道操作符和自定义函数具体怎么使用?能否分享一些最佳实践和常见的安全注意事项?感觉官方文档有些抽象,希望能得到一些具体的代码示例和应用场景说明。谢谢!

3 回复

Go语言内置的text/templatehtml/template是强大的模板引擎。首先,导入包:

import "text/template"

创建模板:

t := template.Must(template.New("example").Parse(`Hello, {{.}}!`))

渲染数据:

name := "Go语言"
err := t.Execute(os.Stdout, name)
if err != nil {
    log.Fatal(err)
}
// 输出: Hello, Go语言!

支持复杂结构:

type Person struct {
    Name string
    Age  int
}
p := Person{Name: "Tom", Age: 25}
template.Must(template.New("").Parse("Name: {{.Name}}, Age: {{.Age}}"))
// 输出: Name: Tom, Age: 25

函数支持与自定义函数:

t := template.Must(template.New("").Funcs(template.FuncMap{
    "upper": strings.ToUpper,
}).Parse("{{upper .}}"))
t.Execute(os.Stdout, "hello")
// 输出: HELLO

注意:html/template专用于HTML场景,会自动转义防止XSS攻击。使用时替换text/template即可。掌握这些基础,可以轻松在Go项目中使用模板引擎。

更多关于Golang教程Go语言中的模板引擎使用指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Go语言内置的text/templatehtml/template是强大的模板引擎。html/template专门用于处理HTML,防止XSS攻击。

首先导入包:import "text/template"import "html/template"

创建模板:

t := template.Must(template.New("example").Parse(`
Hello, {{.}}!
`))

渲染数据:

name := "Go"
err := t.Execute(os.Stdout, name)
if err != nil {
    log.Fatal(err)
}

支持复杂数据结构,如结构体:

type Person struct {
    Name string
    Age  int
}
p := Person{Name: "Alice", Age: 25}
t.Execute(os.Stdout, p)

支持条件、循环等逻辑:

t := template.Must(template.New("").Parse(`
{{if .IsAdmin}}
Admin
{{else}}
User
{{end}}
`))

注意安全:html/template会自动转义HTML,避免注入风险。若需自定义函数或过滤器,可使用Funcs方法注册。例如:

t.Funcs(template.FuncMap{
    "upper": strings.ToUpper,
})

实践时,确保输入数据的安全性,避免潜在漏洞。

Go语言模板引擎使用指南

Go语言内置了强大的模板引擎,分为text/templatehtml/template两个包。以下是主要用法:

基础使用

package main

import (
	"os"
	"text/template"
)

func main() {
	// 定义模板
	tmpl := `Hello, {{.Name}}! Today is {{.Date}}.`

	// 创建模板对象
	t := template.Must(template.New("greeting").Parse(tmpl))

	// 准备数据
	data := struct {
		Name string
		Date string
	}{
		Name: "John",
		Date: "2023-11-15",
	}

	// 执行模板
	t.Execute(os.Stdout, data)
}

常用语法

  1. 变量输出{{.Variable}}
  2. 条件判断
{{if .Condition}} 
  内容1 
{{else}} 
  内容2 
{{end}}
  1. 循环
{{range .Items}}
  {{.}} 
{{end}}
  1. 定义变量
{{$variable := .Value}}

HTML模板

html/template提供HTML安全输出:

package main

import (
	"html/template"
	"os"
)

func main() {
	t := template.Must(template.New("").Parse(
		`<html><body><h1>{{.Title}}</h1><p>{{.Content}}</p></body></html>`))
	
	data := struct {
		Title   string
		Content string
	}{
		Title:   "My Page",
		Content: "This is <b>HTML</b> content",
	}
	
	t.Execute(os.Stdout, data) // 会自动转义HTML
}

模板文件

通常将模板存储在单独文件中:

template.tmpl:

<h1>{{.Title}}</h1>
<ul>
{{range .Items}}
  <li>{{.}}</li>
{{end}}
</ul>

加载模板文件:

t, err := template.ParseFiles("template.tmpl")
if err != nil {
    panic(err)
}

模板引擎是Go Web开发的重要工具,用于分离业务逻辑和显示逻辑。

回到顶部