Maxim Yefremov
Maxim Yefremov

Reputation: 14165

escaping ' to ' in golang html template

How to prevent escaping ' to ' in html template:

package main

import (
    "html/template"
    "os"
)

const tmpl = `<html>
    <head>
        <title>{{.Title}}</title>
    </head>
</html>`

func main() {
    t := template.Must(template.New("ex").Parse(tmpl))
    v := map[string]interface{}{
        "Title": template.HTML("Hello World'"),
    }
    t.Execute(os.Stdout, v)
}

It outputs:

<html>
    <head>
        <title>Hello World&#39;</title>
    </head>
</html>

Desired output:

<html>
    <head>
        <title>Hello World'</title>
    </head>
</html>

playouground

Upvotes: 4

Views: 4077

Answers (1)

xiaq
xiaq

Reputation: 804

@dyoo has explained clearly that <title> content is treated as RCDATA. The code that does the escaping is here. The branch if t == contentTypeHTML is what happens with template.HTML.

If you really need to control the output of the source, use text/template and do the escaping manually.

Upvotes: 1

Related Questions