Go 模板集
模板集是Go中一种特殊的数据类型,它允许你将若干有关联性的模板归为一个组,当然了,它不是一个个体的数据类型,而是被归入了模板的数据结构中。所以,如果你在一些文件中使用了{{define}}…{{end}} 声明,那么这一块就成为了一个模板。
比如一个网页,有头部(Header),主体(Body)以及页脚(Footer),那么这些区域我们都可以在一个文件中定义为一个一个的模板,它们将可以通过一次请求读取到你的程序中,例如:
{{define "header"}}
<html>
<head></head>
{{end}}
{{define "body"}}
<body></body>
{{end}}
{{define "footer"}}
</html>
{{end}}这里的关键知识是:
- 每一个模板都是由 {{define}}…{{end}} 对定义的
- 每一个模板都给定了一个唯一的名称——如果你在一个文件中定义重复使用一个名称将引起一个 Panic
- 不允许将任何字符写在 {{define}}…{{end}}对外——否则会引起Panic
这上面这样的文件被解析为一个模板集之后,Go自动的创建一个以模板名称为键,模板内容为值的 Map:
tmplVar["header"] = pointer to parsed template of text "<html> … </head>"
tmplVar["body"] = pointer to parsed template of text "<body> … </body>"
tmplVar["footer"] = pointer to parsed template of text "</html>"同一个模板集中的模板是知道有其它模板存在的,所以如果有一个模板是可以在各个其它模板中调用的,那么你需要将这个模板单独保存为一个文件,然后再在需要的地方调用它。
现在我们来使用一个简单的示例更好的说明这一切:
- 定义一个模板——使用 {{define}}…{{end}}
- 在一个模板中引入另一个模板——使用 {{template “template name”“}}
- 解析多个文件成为一个模板集——使用 template.ParseFiles
- 执行或者转换模板——使用 template.ExecuteTemplate
先创建两人个模板文件:
- 模板文件一:t1.tmpl
{{define "t_ab"}}a b{{template "t_cd"}}e f {{end}}
上面这个文件将被解析为名为 t_ab 的模板,它还引入了一个名为 t_cd 的模板 - 模板文件二:t2.tmpl
{{define "t_cd"}} c d {{end}}
上面这个文件将被解析为 t_cd 模板
程序代码:
package main
import (
"text/template"
"os"
"fmt"
)
func main() {
fmt.Println("Load a set of templates with {{define}} clauses and execute:")
s1, _ := template.ParseFiles("t1.tmpl", "t2.tmpl") //create a set of templates from many files.
//Note that t1.tmpl is the file with contents "{{define "t_ab"}}a b{{template "t_cd"}}e f {{end}}"
//Note that t2.tmpl is the file with contents "{{define "t_cd"}} c d {{end}}"
s1.ExecuteTemplate(os.Stdout, "t_cd", nil) //just printing of c d
fmt.Println()
s1.ExecuteTemplate(os.Stdout, "t_ab", nil) //execute t_ab which will include t_cd
fmt.Println()
s1.Execute(os.Stdout, nil) //since templates in this data structure are named, there is no default template and so it prints nothing
}输出结果为:
c d
a b c d e ftemplate.ParseGlob 与 template.ParseFiles 类似,只是它只需要接收一个通配符*作为参数,比如上面的这个示例,你可以使用 *template.ParseGlob("t.tmpl”)*也可以得到同样的结果。
评论已关闭