go - Calling a template with several pipeline parameters -


in go template, way pass right data right template feels awkward me. calling template pipeline parameter looks calling function 1 parameter.

let's have site gophers gophers. has home page main template, , utility template print list of gophers.

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

output :

*the great gopherbook*    (logged in dewey)      [most popular]           >> huey         >> dewey         >> louie      [most active]            >> huey         >> louie      [most recent]            >> louie 

now want add bit of context in subtemplate : format name "dewey" differently inside list because it's name of logged user. can't pass name directly because there only one possible "dot" argument pipeline! can do?

  • obviously can copy-paste subtemplate code main template (i don't want because drops interest of having subtemplate).
  • or can juggle kind of global variables accessors (i don't want either).
  • or can create new specific struct type each template parameter list (not great).

you register "dict" function in templates can use pass multiple values template call. call that:

{{template "userlist" dict "users" .mostpopular "current" .currentuser}} 

the code little "dict" helper, including registering template func 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)         := 0; < len(values); i+=2 {             key, ok := values[i].(string)             if !ok {                 return nil, errors.new("dict keys must strings")             }             dict[key] = values[i+1]         }         return dict, nil     }, }).parseglob("templates/*.html") 

Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -