When I'm calling a Go template function to output HTML, it 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" {
return `selected="selected"`
}
return ""
},
"safe": func(s string) template.HTML {
return 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>
I had similar problem with
<img src="{{myfunction}}">
where myfunction return encoded image.Finally I solved it when instead of string function return
template.URL(mystring)
.You are trying to output HTML in a place where template/html thinks is unsafe (for example, inside an HTML element, like this:
I cannot find any way to convince it it is safe (including returning template.HTML instead of string); the only alternative I have found is to rewrite the template, in this example use a bool output instead:
You should wrap the string in an
HTMLAttr
, which was designed for text that gets injected in between angle brackets. Per the documentation:https://golang.org/pkg/html/template/#HTMLAttr
"ZgotmplZ" is a special value that indicates that unsafe content reached a CSS or URL context at runtime. The output of the example will be:
You can add a safe and attr function to the template funcMap:
package main
The output will look like:
You may want to define some other functions which can convert string to template.CSS, template.JS, template.JSStr, template.URL etc.
easiest way:
output
playground Example