Golang 模板变量
Golang template variable
这是我第一次尝试用 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
documentation here:
{{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.
这是我第一次尝试用 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
documentation here:
{{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.