例如,我想在一个源文件中同时使用text/template和html/template.但是下面的代码会抛出错误.
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}}`)
}
Run Code Online (Sandbox Code Playgroud)
Mos*_*afa 238
import (
"text/template"
htemplate "html/template" // this is now imported as htemplate
)
Run Code Online (Sandbox Code Playgroud)
在规范中阅读更多相关信息.
Ina*_*mus 10
回答莫斯塔法是正确的,但它需要一些解释.让我试着回答一下.
它不起作用,因为:
import "html/template"
import "text/template"
Run Code Online (Sandbox Code Playgroud)
在这些行中,您尝试导入两个具有相同名称的"模板"包.
进口是一种声明
您不能在同一范围内声明相同的名称(术语:标识符).
在Go中,import是一个声明,其范围是尝试导入这些包的文件.
它不起作用,因为你不能在同一个块中声明具有相同名称的变量.
这就是为什么这样做的原因
package main
import (
t "text/template"
h "html/template"
)
func main() {
t.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
h.New("foo").Parse(`{{define "T"}}Hello, {{.}}!{{end}}`)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
43146 次 |
| 最近记录: |