How to import and use different packages of the same name

hardPass picture hardPass · May 2, 2012 · Viewed 53.7k times · Source

For example, I want to use both text/template and html/template in one source file. But the code below throw errors.

import (
    "fmt"
    "net/http"
    "text/template" // template redeclared as imported package name
    "html/template" // template redeclared as imported package name
)

func handler_html(w http.ResponseWriter, r *http.Request) {
    t_html, err := html.template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
    t_text, err := text.template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)

}

Answer

Mostafa picture Mostafa · May 2, 2012
import (
    "text/template"
    htemplate "html/template" // this is now imported as htemplate
)

Read more about it in the spec.