199

For example, I want to use both the text/template and html/template packages 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}}`) } 
0

2 Answers 2

353
import ( "text/template" htemplate "html/template" // this is now imported as htemplate ) 

Read more about it in the spec.

Sign up to request clarification or add additional context in comments.

2 Comments

Any convention on how we should name the imported package? Short and small case is general recommendation. But what in case we can't come up with any meaningful short name? Which one is preferable - multi_word or multiWord?
It is generally advised to use camel casing for multi word import names. import ( multiWord "multi/word" )
46

Answer by Mostafa is correct however it demands some explanation. Let me try to answer it.

Your example code doesn't work because you're trying to import two packages with the same name, which is: " template ".

import "html/template" // imports the package as `template` import "text/template" // imports the package as `template` (again) 

Importing is a declaration statement:

  • You can't declare the same name (terminology: identifier) in the same scope.

  • In Go, import is a declaration, and its scope is the file that's trying to import those packages.

  • It doesn't work because of the same reason that you can't declare variables with the same name in the same block.

The following code works:

package main import ( "text/template" htemplate "html/template" ) func main() { template.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) htemplate.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`) } 

The code above gives two different names to the imported packages with the same name. So, there are now two different identifiers that you can use: template for the text/template package and htemplate for the html/template package.

You can check it on the playground.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.