Golang Template

今天来讲讲 golang 中的标准库 template, Go标准库提供了几个 package 可以产生输出结果, 主要有2个: text/template 和 html/template, text/template 提供根据模板输出内容, html/template 产生安全的 HTML 的输出, 这两个库的使用方式很相似,文中的例子大部分是基于 html/template 展示的。

解析和创建模板

模板命名

template 所使用的库没有限定扩展名, 但最经常使用的后缀是 .tmpl, 编辑器对.tmpl的支持最好, 官方的例子也是使用 .tmpl, .tpl 也经常使用。

创建模板

通过 Parse 方法可以创建文件名为名字的模板。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package main

import (
	"fmt"
	"html/template"
	"log"
)

func main() {
	tpl, err := template.New("index").Parse("index.tmpl")
	if err != nil {
		log.Fatalln(err)
	}

}

解析多个模板

通过 template.ParseFiles(filenames …string) 方法可以解析一组模板, 使用各个文件名作为模板名称。

template.ParseGlob(pattern) 方法会根据pattern解析所有匹配的模板并保存。

1
2
3
4
5
6
7
8
package main

import "html/template"

func main() {
	template.ParseFiles("index.tmpl", "index2.tmpl")

}

解析字符串模板

除了可以解析文件, 还可以解析字符串模板。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18

package main

import "html/template"

const goTemplate = `
package main 

import "fmt"

func main() {
	fmt.Println("hello")
}
`

func main() {
	t, err := template.New("go").Parse(goTemplate)
}

解析模板

解析模板

模板tpl可以通过tpl.Execute(io.Writer, data)去执行, 模板渲染后的内容写入到io.Writer中。Data是传给模板的动态数据。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
package main

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

func tmpl(w http.ResponseWriter, r *http.Request) {
	t1, err := template.ParseFiles("c2.1/index.tmpl")
	if err != nil {
		panic(err)
	}
	t1.Execute(w, "hello world")
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.HandleFunc("/tmpl", tmpl)
	server.ListenAndServe()
}

模板文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{{ . }}
</body>
</html>

我们来看看解析后的文件吧: img.png 怎么样,很神奇吧。

模板变量

.

模板变量可以是boolean, string, character, integer, floating-point, imaginary 或者 complex constant。传给模板这样的数据就可以通过点号.来访问: {{ . }} 如果想访问复杂的变量, 可以通过 {{ .fileds }} 的方式访问。

模板语句

在模板里也可以使用我们编程中常用的判断和循环逻辑。

判断

我们可以使用 if 检查数据,如果不满足可以执行 else 逻辑。空值是是 false , 0 、nil、空字符串或者长度为0的字符串都是 false 。

1
<h1>Hello, { {if .Name}} { {.Name}} { {else}} Anonymous { {end}}!</h1>

如果 .Name 变量存在,会输出Hello, Name,否则输出Hello, Anonymous。 模板也提供了{ { else if .Name2 }}处理多个分支。

Range

模板也提供了 range 关键字用来循环读取变量。

小结

以上就是我今天讲述的 go 标准库 template 的简单使用,在以后可能还会讲一讲在模板中如何自定义函数。

参考链接