Home > Backend Development > Golang > Escape '/' in templates

Escape '/' in templates

WBOY
Release: 2024-02-06 09:45:08
forward
1173 people have browsed it

Escape / in templates

Question content

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}}
Copy after login

But I still get "undefined function 'unescape'". Is unescape not defined?

"net/url" has been imported.


Correct answer


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"))
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template