提问人:SapphireSun 提问时间:10/3/2023 最后编辑:SapphireSun 更新时间:10/3/2023 访问量:41
Golang 模板变量未呈现
Golang Template Variable Not Rendering
问:
希望这对你们来说是一个非常简单的问题。我是 Golang 的新手。我已经向 ChatGPT 寻求帮助,但我们无法弄清楚。
我有一个 HTML 页面,我想使用基数和插入基数的部分来呈现该页面。由于某种原因,我无法渲染变量。这是我的模板代码:
{{define "BASE"}}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My site</title>
<link rel="icon" type="image/png" href="/image/favicon.png" sizes="96x96"/>
{{block "STYLES" .}}{{end}}
{{block "SCRIPTS" .}}{{end}}
</head>
<body>
{{block "CONTENT" .}}{{end}}
</body>
</html>
{{end}}
{{define "CONTENT"}}
Title: {{.title}}
{{end}}
{{template "BASE"}}
这是我的 Go 代码:
import "html/template"
import "os"
func main () {
temp := template.Must(template.ParseFiles("www/html/test.tpl"))
temp.Execute(os.Stdout, map[string]string{"title":"MYTITLE"})
}
这是我的输出:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My site</title>
<link rel="icon" type="image/png" href="/image/favicon.png" sizes="96x96"/>
</head>
<body>
Title:
</body>
</html>
正如你所看到的,.title 变量不呈现。谁能告诉我为什么?
我也认为我必须放入模板本身有点奇怪。我正在使用 Gin,除非我这样做,否则它似乎不会渲染任何东西。{{template "BASE"}}
如果我使用删除的,它可以工作。我用错了杜松子酒吗?temp.ExecuteTemplate(os.Stdout, "BASE", ...)
{{template "BASE"}}
答: 暂无答案
评论
{{define "template_name"}}
{{end}}
</html>
{{ define "template_name"}}
{{template ...}}
.title
{{template "BASE"}}
{{template "BASE" .}}