Calling a template with several pipeline parameters

You could register a “dict” function in your templates that you can use to pass multiple values to a template call. The call itself would then look like that:

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

The code for the little “dict” helper, including registering it as a template func is here:

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")

Leave a Comment

tech