You can achieve this in several ways:
1. With a custom function
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.
2. Modifying 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).
3. Adding a method to 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.