Golang模板函数使用范例
html/template包中的模板函数:
本包中提供的功能有限,所以很多时候需要使用用户定义的函数来辅助渲染页面。下面讲讲模板函数如何使用。
函数声明:
/* Funcs adds the elements of the argument map to the template's function map.It panics if a value in the map is not a function with appropriate return type. However, it is legal to overwrite elements of the map. The return value is the template, so calls can be chained.
*/
func (t *Template) Funcs(funcMap FuncMap) *Template
Funcs函数就是用来创建我们模板函数的函数了,它需要一个FuncMap类型的参数,继续看手册
/* FuncMap is the type of the map defining the mapping from names to functions. Each function must have either a single return value, or two return values of which the second has type error. In that case, if the second (error) argument evaluates to non-nil during execution, execution terminates and Execute returns that error. FuncMap has the same base type as FuncMap in "text/template", copied here so clients need not import "text/template".
*/
type FuncMap map[string]interface{}
使用方法:
例一:
函数定义:
func SpliteByCommaAndGetFirst(str string) string {
return strings.Split(str, ",")[0]
}
模板绑定模板函数:
- 创建一个FuncMap类型的map,key是模板函数的名字,value是其函数的定义。
- 将 FuncMap注入到模板中。
funcMap := template.FuncMap{"SpliteByCommaAndGetFirst": SpliteByCommaAndGetFirst}
t := template.New("agents_info.html").Funcs(funcMap)
t =template.Must(t.ParseFiles("./ui/templates/agents_info.html"))
err := t.ExecuteTemplate(w, "agents_info.html", agentsInfo)
if err != nil {
fmt.Println(err)
}
模板中如何使用:
{{SpliteByCommaAndGetFirst .Version}}
注意:
- 函数的注入,必须要在parseFiles之前,因为解析模板的时候,需要先把函数编译注入。
- Template object can have multiple templates in it and each one has a name. If you look at the implementation of ParseFiles, you see that it uses the filename as the template name inside of the template object. So, name your file the same as the template object, (probably not generally practical) or else use ExecuteTemplate instead of just Execute.
- The name of the template is the bare filename of the template, not the complete path。如果模板名字写错了,执行的时候会出现:”**” is an incomplete or empty template
例二:
函数定义:
func SpliteByCommaAndGetFirst(str string) string {
return strings.Split(str, ",")[0]
}
func Add(a,b int)int{
return a+b
}
绑定模板函数:
funcMap := template.FuncMap{"SpliteByCommaAndGetFirst": SpliteByCommaAndGetFirst, "Add":Add}
t, err := template.New("layout.html").Funcs(funcMap).ParseFiles("template/html/layout.html","template/html/result_default.html")
err = t.Execute(w, temp)
模板中如何使用:
{{SpliteByCommaAndGetFirst .Version}}
{{And 1 2}}
例三:
t, err := template.New("_base.html").Funcs(funcs).ParseFiles("../view/_base.html", "../view/home.html")
if err != nil {
fmt.Fprint(w, "Error:", err)
fmt.Println("Error:", err)
return
}
err = t.Execute(w, data)
if err != nil {
fmt.Fprint(w, "Error:", err)
fmt.Println("Error:", err)
}
The name of the template is the bare filename of the template, not the complete path. Execute will execute the default template provided it’s named to match, so there’s no need to use ExecuteTemplate.
In this case, _base.html file is the outermost container, eg:
<!DOCTYPE html>
<html><body>
<h1>{{ template "title" }}</h1>
{{ template "content" }}
</body></html>
while home.html defines the specific parts:
{{ define "title" }}Home{{ end }}
{{ define "content" }}
Stuff
{{ end }}