Html/template still escaping template.URL in <a href>?

I’m trying to render a template.URL in an <a href> context, but it always comes out with &amp;s instead of ampersands. What am I missing?

Playground here

package main

import (
	"html/template"
	"os"
)

func main() {
	template.Must(template.New("Template").Parse(`
		Want:
			<a href="http://www.google.com?foo=bar&baz=qux">foo</a>
			
		Got:
			<a href="{{ . }}">foo</a>
	`)).Execute(os.Stdout, template.URL("http://www.google.com?foo=bar&baz=qux"))
}

Output:

		Want:
			<a href="http://www.google.com?foo=bar&baz=qux">foo</a>
			
		Got:
			<a href="http://www.google.com?foo=bar&amp;baz=qux">foo</a>

Hey @blangenfeld,

&'s being escaped to &amp; is actually correct encoding.

Here’s a quick example based on your code to show you that the link actually gets rendered correctly (go to http://localhost:9000):

package main

import (
	"html/template"
	"log"
	"net/http"
)

var tmpl = template.Must(template.New("template").Parse(`
	Want: <a href="http://www.google.com?foo=bar&baz=qux">foo</a>
	<br />
	Got: <a href="{{.}}">foo</a>
`))

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-type", "text/html")

		err := tmpl.Execute(w, template.URL("http://www.google.com?foo=bar&baz=qux"))
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	log.Fatal(http.ListenAndServe(":9000", nil))
}

If you actually wanted to write a link to os.Stdout without the &amp; encoding, you could simply pass the whole link tag as html into a template instead of what’s just inside of the quotes:

t := template.Must(template.New("template").Parse(`{{.}}`))
err := t.Execute(os.Stdout, template.HTML(`<a href="http://www.google.com?foo=bar&baz=qux">foo</a>`))
if err != nil {
	log.Fatalln(err)
}

I found a post which goes into the technical details, citing the HTML 4 and 5 standards. Yes, encoding the ampersands is correct.

This is a bit late, but here is a blog post that covers some of the encoding contexts used by Go: http://www.calhoun.io/an-intro-to-templates-in-go-part-1-of-3/

I find that it helps to have a broad overview of what Go encodes and when to expect it to avoid issues like this.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.