Reputation: 129
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 <
. 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:
<@user1> <@user2>
How to fix this?
Upvotes: 3
Views: 916
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, <script>alert('you have been pwned')</script>!
Upvotes: 2