Golang模板使用中遇到的问题及解决方案
Golang模板使用中遇到的问题及解决方案
package main
import (
"text/template"
"os"
)
var fm = template.FuncMap{
"mul2": double,
}
func double(x float64) float64 {
return x * 2
}
var x = 10.0
var tpl *template.Template
func main() {
tpl = template.Must(template.New("").Funcs(fm).ParseFiles("templates/index.html"))
tpl.ExecuteTemplate(os.Stdout,"index.html" , x) //这行代码可以工作
tpl.Execute(os.Stdout, x) // 这行代码没有显示任何输出
}
只有当我指定要执行哪个模板时,它才能正常工作,否则就不行。 有什么想法吗?
更多关于Golang模板使用中遇到的问题及解决方案的实战教程也可以访问 https://www.itying.com/category-94-b0.html
3 回复
你试过使用…router.LoadHTMLGlob("/templates/*")吗?
问题出在模板解析和执行的方式上。当使用 ParseFiles 解析多个模板文件时,每个文件都会创建一个独立的模板,而 Execute 方法默认执行的是主模板(没有名称的模板),但你的主模板实际上是空的。
以下是详细解释和解决方案:
问题分析
template.New("").Funcs(fm).ParseFiles("templates/index.html")创建了一个主模板(空名称),同时解析了index.html文件ExecuteTemplate明确指定了要执行"index.html"模板,所以能正常工作Execute尝试执行主模板(空名称),但这个模板没有内容
解决方案
方案1:使用明确的模板名称(推荐)
package main
import (
"text/template"
"os"
)
var fm = template.FuncMap{
"mul2": double,
}
func double(x float64) float64 {
return x * 2
}
var x = 10.0
var tpl *template.Template
func main() {
// 明确命名模板
tpl = template.Must(template.New("main").Funcs(fm).ParseFiles("templates/index.html"))
// 两种方式都能工作
tpl.ExecuteTemplate(os.Stdout, "index.html", x)
tpl.Execute(os.Stdout, x) // 现在这会执行名为"main"的模板
}
方案2:使用 Parse 而不是 ParseFiles
package main
import (
"text/template"
"os"
)
var fm = template.FuncMap{
"mul2": double,
}
func double(x float64) float64 {
return x * 2
}
var x = 10.0
var tpl *template.Template
func main() {
// 直接解析模板内容
tplStr := `Value: {{.}}, Double: {{mul2 .}}`
tpl = template.Must(template.New("").Funcs(fm).Parse(tplStr))
tpl.Execute(os.Stdout, x) // 这会正常工作
}
方案3:使用 Lookup 方法
package main
import (
"text/template"
"os"
)
var fm = template.FuncMap{
"mul2": double,
}
func double(x float64) float64 {
return x * 2
}
var x = 10.0
var tpl *template.Template
func main() {
tpl = template.Must(template.New("").Funcs(fm).ParseFiles("templates/index.html"))
// 获取特定的模板并执行
if tmpl := tpl.Lookup("index.html"); tmpl != nil {
tmpl.Execute(os.Stdout, x) // 这会正常工作
}
}
完整工作示例
package main
import (
"text/template"
"os"
)
var fm = template.FuncMap{
"mul2": double,
}
func double(x float64) float64 {
return x * 2
}
var x = 10.0
func main() {
// 创建并命名主模板
tpl := template.Must(template.New("main").Funcs(fm).Parse("Main template: {{.}}, Double: {{mul2 .}}"))
// 现在 Execute 会正常工作
tpl.Execute(os.Stdout, x)
// 输出: Main template: 10, Double: 20
}
关键点是:当使用 ParseFiles 时,每个文件都会创建一个以文件名命名的模板,而主模板(空名称)保持为空,除非你明确为其定义内容。

