html/template escaping problem

79 views
Skip to first unread message

Jens-Uwe Mager

unread,
Sep 9, 2019, 7:53:34 AM9/9/19
to golang-nuts
I am having a problem to properly escape javascript urls in my templates. I do have the situation where I build a template that is having javascript urls that are from variables in the go program (read from yaml files). The go program generates static html, but the html is supposed to use moustache.js to expand some further variables at render time. I am just not able to preserve my javascript from the html/template escaping. Any ideas what I am doing wrong? 

The output is:

<a href="javascript:doSlide%28%27%7b%7barea%7d%7d%27%29;">{{test}}</a>

But I would like it to be:

<a href="javascript:doSlide('{{area}}');">{{test}}</a>


package main

import (
"html/template"
"os"
)

var t = template.Must(template.New("test").Funcs(template.FuncMap{
"safeattr": func(value string) template.HTMLAttr {
return template.HTMLAttr(value)
},
"safehtml": func(value string) template.HTML {
return template.HTML(value)
},
"safejs": func(value string) template.JS {
return template.JS(value)
},
"safecss": func(value string) template.CSS {
return template.CSS(value)
},
"safeurl": func(value string) template.URL {
return template.URL(value)
},
}).Parse(`
<a href="{{safeurl .href}}">{{safehtml .content}}</a>
`))

func main() {
data := map[string]string{
"href":    "javascript:doSlide('{{area}}');",
"content": "{{test}}",
}
err := t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}





Kurtis Rader

unread,
Sep 9, 2019, 10:20:06 AM9/9/19
to Jens-Uwe Mager, golang-nuts
You have

    href="{{safeurl .href}}",

Shouldn't that be "safejs"? Using "safehref" is causing the string to be hex encoded as a URL. Which means most special chars will be converted to hex representation.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/0c93e49c-1e8b-4617-baef-0848b57fde93%40googlegroups.com.


--
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank

Jens-Uwe Mager

unread,
Sep 9, 2019, 12:13:54 PM9/9/19
to golang-nuts
This gives me the output:

<a href="#ZgotmplZ">{{test}}</a>


So this does not work at all.
To unsubscribe from this group and stop receiving emails from it, send an email to golan...@googlegroups.com.

Jens-Uwe Mager

unread,
Sep 11, 2019, 9:59:58 AM9/11/19
to golang-nuts
I finally got a workaround going, and that is to not have any moustache template in the javascript at all. By putting the {{area}} template in an data-xxx attribute of the <a> element I can access this from the javascript.
Reply all
Reply to author
Forward
0 new messages