xu feng
xu feng

Reputation: 129

escape template in range

I want to print user list like: <@user1> <@user2>, this is an internal format in my company internal, but the golang template always escape the < to &lt;. My code:

tpl, _ := template.New("text").Parse(`{{range .Users}} <@{{.}}> {{end}}`)
var buffer bytes.Buffer
tpl.Execute(&buffer, struct {
    Users []string
}{
    Users: []string{"user1", "user2"},
})
fmt.Println(buffer.String())

expect:

<@user1> <@user2>

output:

 &lt;@user1>  &lt;@user2> 

How to fix this?

Upvotes: 3

Views: 916

Answers (1)

AndrewViscu
AndrewViscu

Reputation: 36

If you want to do so, use text/template. Here's a part of documentation for better understanding each:

Godoc: html/template:

This package wraps package text/template so you can share its template API to parse and execute HTML templates safely.

tmpl, err := template.New("name").Parse(...)
// Error checking elided
err = tmpl.Execute(out, data)

If successful, tmpl will now be injection-safe. Otherwise, err is an error defined in the docs for ErrorCode.

HTML templates treat data values as plain text which should be encoded so they can be safely embedded in an HTML document. The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts.

The security model used by this package assumes that template authors are trusted, while Execute's data parameter is not. More details are provided below.

Example

import "text/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

produces

Hello, <script>alert('you have been pwned')</script>!

but the contextual autoescaping in html/template

import "html/template"
...
t, err := template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
err = t.ExecuteTemplate(out, "T", "<script>alert('you have been pwned')</script>")

produces safe, escaped HTML output

Hello, &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;!

Upvotes: 2

Related Questions