Reputation: 4409
How do I escape HTML when I have an array field in a struct?
For a single show page, this code works:
show.go:
err := ShowTmpl.ExecuteTemplate(w, "show.html", struct {
Title string
SafeBody template.HTML
}{
t.Title,
template.HTML(t.BodyHTML),
})
For an index page:
index.go
type as struct {
Articles []*Article
}
var a as
// some code to give a.Articles its values
err := IndexTmpl.ExecuteTemplate(w, "index.html", a)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
index.html:
{{with .Articles}}
{{range .}}
<a href="/">{{.Title}}</a>
{{.BodyHTML | html}} // Doesn't work
{{end}}
{{end}}
How do I escape HTML when I'm ranging over a struct field?
Upvotes: 2
Views: 293
Reputation: 417472
You can achieve this in several ways:
You can use a custom function. The Template.Funcs()
method allows you to register any custom functions which can be invoked from templates.
Create a simple function which converts a string
to template.HTML
like this:
func ToHtml(s string) template.HTML {
return template.HTML(s)
}
You can register it like this:
t := template.Must(template.New("index.html").
Funcs(map[string]interface{}{"ToHtml": ToHtml}).Parse(indexHtml))
Where just for demonstration purposes indexHtml
is a string
of your template:
const indexHtml = `{{with .}}
{{range .}}
<a href="/">{{.Title}}</a>
{{ToHtml .BodyHTML}}
{{end}}
{{end}}
`
And you can refer to it and call it from the template like this:
{{ToHtml .BodyHTML}}
Calling this template with a parameter:
a := []struct {
Title string
BodyHTML string
}{{"I'm the title", "I'm some <b>HTML</b> code!"}}
err := t.ExecuteTemplate(os.Stdout, "index.html", a)
Here's the complete, working example on the Go Playground.
Article
If you can, it would be easier to just change the type of Article.BodyHTML
to template.HTML
and then it would be rendered unescaped without further ado. This would also make the intent clear (that it should/does contain safe HTML which will be rendered unescaped).
Article
You can also add a method to the Article
type which would return its BodyHTML
field as a template.HTML
(pretty much what the custom function does in proposition #1):
func (a *Article) SafeBody() template.HTML {
return template.HTML(a.BodyHTML)
}
Having this method you can simply call it from the template:
{{range .}}
<a href="/">{{.Title}}</a>
{{.SafeBody}}
{{end}}
Try this variant on the Go Playground.
Upvotes: 2