go - Golang template FuncMap that can call itself -


i trying achieve function add funcmaps in base template, , function should used render re-useable view components

for instance:

func (v *item) rendercomponent(componentpath string, vars ...interface{}) template.html {     p := path.join(v.folder, "components", componentpath)      // pieces of component path.     componentpathpieces := strings.split(p, "/")      // last item in pieces (this should file name).     componentfilename := componentpathpieces[len(componentpathpieces)-1]      // make new template using component file name , add funcmap functions.     t := template.new(componentfilename).funcs(v.funcmap)      // determine if there error in template syntax.     t, err := template.parsefiles(p + "." + v.extension)     if err != nil {         panic(err)     }      // add variables component , write buffer.     b := new(bytes.buffer)     if err = t.execute(b, vars); err != nil {         panic(err)     }      // return contents of template buffer string of html.     return template.html(b.string()) } 

this code works fine component doesn't render component. example, can write {{component "buttons/default-button" "some url goes here"}} , render component @ components/button/default-button.tmpl fine.

however, if include component within default-button component, such {{component "icons/check-icon"}}, large error (too big paste here). here 1 of error messages:

template: default-button.tmpl:4: function "component" not defined

as can see, error thrown component file trying call component. believe happens because viewfunc either not being added, or being recursively called in way.

oops, looked had typo.

had change this:

// make new template using component file name , add funcmap functions. t := template.new(componentfilename).funcs(v.funcmap)  // determine if there error in template syntax. t, err := template.parsefiles(p + "." + v.extension) 

...to this:

// make new template using component file name , add funcmap functions. t := template.new(componentfilename + "." + v.extension).funcs(v.funcmap) // <---- 'componentfilename' 'componentfilename + "." + v.extension'  // determine if there error in template syntax. t, err := t.parsefiles(p + "." + v.extension) // <---- 'template' 't' 

i referencing template package instead of t template created. passed in wrong name template.new, since expects full fill such index.tmpl, instead of index.

now works expected! can call component component.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -