问题描述
这是我第一次尝试用 Go 做前端。 我有这个模板:
{{define "index"}}{{template "_header.html"}}
{{template "_message.html"}}
<div>Page Index</div>
<div>Welcome {{.Title}}</div>
{{template "_footer.html"}}
{{end}}
{{.Title}}
按预期工作的地方。
但是当我尝试在包含文件 {template "_header.html"}
中使用它时,它失败了。
{{define "_header.html"}}<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="utf-8">
<Meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css"/>
<link rel="stylesheet" href="./css/css.css"/>
<title>{{.Title}}</title>
</head><body>{{end}}
现在 <title>
标签为空。
有什么建议吗?
解决方法
根据模板文档,使用 {{ template "name" }}
将 nil 数据传递给您的模板。因此,没有要渲染到 {{ .Title }}
中的数据。您需要使用 {{ template "name" pipeline }}
将数据传递到包含的模板中。
在您的情况下,{{ template "_header.html" . }}
应该可以解决问题,将当前数据对象传递到您包含的模板中。
{{template "name"}}
The template with the specified name is executed with nil data.
{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.