首页 > 文章列表 > 使用多个管道参数调用模板

使用多个管道参数调用模板

golang
196 2023-03-08

问题内容

在 Go 模板中,有时将正确的数据传递给正确的模板的方式让我感觉很尴尬。调用带有管道参数的模板看起来就像调用只有一个参数的函数。

假设我有一个关于 Gophers 的 Gophers 网站。它有一个主页主模板和一个打印 Gophers 列表的实用程序模板。

http://play.golang.org/p/Jivy_WPh16

输出 :

*The great GopherBook*    (logged in as Dewey)

    [Most popular]  
        >> Huey
        >> Dewey
        >> Louie

    [Most active]   
        >> Huey
        >> Louie

    [Most recent]   
        >> Louie

现在我想在子模板中添加一些上下文:在列表中以不同的方式格式化名称“Dewey”,因为它是当前登录用户的名称。但我不能直接传递名称,因为[只有一个](http://golang.org/pkg/text/template/#hdr- Actions)可能的“点”参数管道!我能做些什么?

  • 显然,我可以将子模板代码复制粘贴到主模板中(我不想这样做,因为它放弃了拥有子模板的所有兴趣)。
  • 或者我可以使用访问器处理某种全局变量(我也不想这样做)。
  • 或者我可以为每个模板参数列表创建一个新的特定结构类型(不是很好)。

正确答案

您可以在模板中注册一个“dict”函数,您可以使用该函数将多个值传递给模板调用。调用本身将如下所示:

{{template "userlist" dict "Users" .MostPopular "Current" .CurrentUser}}

小“dict”助手的代码,包括将其注册为模板 func 在这里:

var tmpl = template.Must(template.New("").Funcs(template.FuncMap{
    "dict": func(values ...interface{}) (map[string]interface{}, error) {
        if len(values)%2 != 0 {
            return nil, errors.New("invalid dict call")
        }
        dict := make(map[string]interface{}, len(values)/2)
        for i := 0; i < len(values); i+=2 {
            key, ok := values[i].(string)
            if !ok {
                return nil, errors.New("dict keys must be strings")
            }
            dict[key] = values[i+1]
        }
        return dict, nil
    },
}).ParseGlob("templates/*.html")