Golang模板函数使用范例

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]
}

模板绑定模板函数:

  1. 创建一个FuncMap类型的map,key是模板函数的名字,value是其函数的定义。
  2. 将 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}}

注意:

  1. 函数的注入,必须要在parseFiles之前,因为解析模板的时候,需要先把函数编译注入。
  2. 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.
  3. 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 }}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值