Home >Backend Development >Golang >Escape '/' in templates
I want to pass a string like "avatars/avatar.png", but when I pass it to the template, I get character escapes. So I wrote a function that is passed to the template:
var tpl *template.Template func init() { tpl = template.Must(template.ParseGlob("1Forum/static/html/*.html")) tpl = tpl.Funcs(template.FuncMap{ "unescape": func(s string) string { unescaped, err := url.PathUnescape(s) if err != nil { return s } return unescaped }, }) } {{unescape .User.Avatar}}
But I still get "undefined function 'unescape'". Is unescape not defined?
"net/url" has been imported.
unescape is not defined?
Technically no. You did define it, but you did so too late. Whether a function is defined is checked during parsing, not during execution. You have parseglob
and then you do tpl.func(...)
. It's not normal.
Instead do this:
func init() { tpl = template.Must(template.New("t").Funcs(template.FuncMap{ "unescape": func(s string) string { unescaped, err := url.PathUnescape(s) if err != nil { return s } return unescaped }, }).ParseGlob("1Forum/static/html/*.html")) }
Please note that escaping is a safe feature and its occurrence depends on the context you are using the data in, and unescape
probably won't help you "cheat" your way around, since the escaping will be done on the output
of unescape, not its input.
In other words, when you do {{unescape .}}
, the parser may convert it to {{unescape . | urlescaper}}
depending on the context (urlescaper
is an internal escaping function). To avoid this, when you want to use a known safe string verbatim in a template, you should use input string instead of unescape
.
See Playground Example.
For more information about context, escaping, typing strings, etc., read the package's documentation , everything is explained clearly.
The above is the detailed content of Escape '/' in templates. For more information, please follow other related articles on the PHP Chinese website!