Reputation: 773
When i pass argument to onclick function i got spaces around that argument, why and how remove them?
t, _ := template.New("").Parse(`<div onclick="test({{.}})">{{.}}</div>`)
t.Execute(os.Stdout, 1)
Result:
<div onclick="test( 1 )">1</div>
Edit:
Updated by Dave help, from template we can do something like this:
t, _ := template.New("").Funcs(template.FuncMap{
"test": func(i interface{}) template.JS {
switch i.(type) {
case int:
s := strconv.Itoa(i.(int))
return template.JS(s)
// other types
default:
panic("bad type")
}
},
}).Parse(`<div onclick="test({{test .}})">{{.}}</div>`)
t.Execute(os.Stdout, 1)
Upvotes: 0
Views: 94
Reputation: 64657
It's a result of Golang doing some things to ensure that malicious JS doesn't end up in your template. If you specify that what you are passing in is safe for javascript, it will work fine.
type JS
Use of this type presents a security risk: the encapsulated content should come from a trusted source, as it will be included verbatim in the template output.
https://play.golang.org/p/TUOECg1YDtl
t.Execute(os.Stdout, template.JS("1"))
Result:
<div onclick="test(1)">1</div>
Upvotes: 1