Wednesday, 15 May 2013

Why am I seeing ZgotmplZ in my Go HTML template output? -



Why am I seeing ZgotmplZ in my Go HTML template output? -

when i'm calling go template function output html, displays zgotmplz.

sample code:

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

package main import ( "html/template" "os" ) func main() { funcmap := template.funcmap{ "printselected": func(s string) string { if s == "test" { homecoming `selected="selected"` } homecoming "" }, "safe": func(s string) template.html { homecoming template.html(s) }, } template.must(template.new("template").funcs(funcmap).parse(` <option {{ printselected "test" }} {{ printselected "test" | safe }} >test</option> `)).execute(os.stdout, nil) }

output:

<option zgotmplz zgotmplz >test</option>

"zgotmplz" special value indicates unsafe content reached css or url context @ runtime. output of illustration be

<img src="#zgotmplz">

you can add together safe , attr function template funcmap:

package main

import ( "html/template" "os" ) func main() { funcmap := template.funcmap{ "attr":func(s string) template.htmlattr{ homecoming template.htmlattr(s) }, "safe": func(s string) template.html { homecoming template.html(s) }, } template.must(template.new("template").funcs(funcmap).parse(` <option {{ .attr |attr }} >test</option> {{.html|safe}} `)).execute(os.stdout, map[string]string{"attr":`selected="selected"`,"html":`<option selected="selected">option</option>`})

}

the output looks like:

<option selected="selected" >test</option> <option selected="selected">option</option>

you may want define other functions can convert string template.css,template.js,template.jsstr,template.url etc.

go go-templates

No comments:

Post a Comment