Golang模板参数传递与执行指南
Golang模板参数传递与执行指南 以下代码可以正常工作
tpl.ExecuteTemplate(w, "index.html", data)
但传递参数时,以下代码无法工作。我该如何使其正常工作?
page := template.HTML("index.html")
tpl.ExecuteTemplate(w, page, data)
是否出现了错误?
./main.go:84:27: cannot use page (type func(http.ResponseWriter, *http.Request)) as type string in argument to tpl.ExecuteTemplate
更多关于Golang模板参数传递与执行指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html
Sibert:
不起作用
发生了什么事?你收到错误了吗?
更多关于Golang模板参数传递与执行指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
我想我找到了解决方案。可能是变量作用域的问题。
path := strings.Trim(r.URL.Path, "/")
var page string <--- 变量作用域?
switch path {
case "":
page = "index.html"
fmt.Println(page, list)
default:
page = path + ".html"
fmt.Println(page, list)
}
err = tpl.ExecuteTemplate(w, page, list)
在Go模板中,ExecuteTemplate的第二个参数必须是字符串类型,指定要执行的模板名称。你的代码尝试传递template.HTML类型,这会导致类型不匹配。
template.HTML类型用于标记已经安全的HTML内容,防止转义,而不是用于指定模板名称。以下是正确的做法:
// 正确方式:直接使用字符串作为模板名称
tpl.ExecuteTemplate(w, "index.html", data)
如果你需要动态决定模板名称,可以使用字符串变量:
// 动态模板名称示例
templateName := "index.html"
if condition {
templateName = "other.html"
}
tpl.ExecuteTemplate(w, templateName, data)
如果你确实需要将HTML内容作为参数传递,应该使用数据参数(第三个参数):
// 将HTML内容作为数据传递
data := struct {
Title string
Content template.HTML
}{
Title: "首页",
Content: template.HTML("<h1>欢迎</h1>"),
}
tpl.ExecuteTemplate(w, "base.html", data)
然后在模板中安全输出HTML内容:
<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
<title>{{.Title}}</title>
</head>
<body>
{{.Content}}
</body>
</html>
错误信息显示你尝试传递函数类型,这完全不符合ExecuteTemplate的参数要求。请确保第二个参数始终是字符串类型的模板名称。

