不确定如何正确命名。
有没有办法编写一个主模板和许多片段,并根据URL用户请求注入所需的片段。 假设我有 / customers / profile 和 / customers / projects 。我想编写一个主要的 customer.html 模板文件和一个 customer-includes.html 文件,其中包含2个 {{define“ profile”}} 和 {{定义“项目”}} 片段。 然后,我想有2个处理程序来处理 / customers / profile 和 / customers / projects 并执行 customer.html 模板。 但是,当用户转到URL / customers / profile 时,我想插入主模板 {{template“ profile”。 }} ,如果他去 / customers / projects ,我想注入 {{模板“ projects”。 }} 。 做这个的最好方式是什么? 我假设我需要在其中使用某种{{if / else}}。如下例。但是mby有更好的方法。
{{ if ( eq .Section "customer-profile") }} // Could be replaced with Page ID
{{ template "profile" . }}
{{ else }}
{{ template "projects" . }}
{{ end}}
答案 0 :(得分:3)
您可以为此使用模板块。
templates/customers-base.html
:
<html>
<head>
<title>{{.title}}</title>
<link rel="stylesheet" type="text/css" href="static/styles.css">
<!-- You can include common scripts and stylesheets in the base template -->
</head>
<body>
{{block "BODY" .}}
{{end}}
</body>
</html>
templates/customers-projects.html
:
{{define "BODY"}}
<h1>Your Projects</h1>
<p>Normal template goes here</p>
<p>{{.myvar}}<p>
{{end}}
您可以为templates/customers-profile.html
复制此格式。
您的项目代码:
data := map[string]interface{}{
"title": "Base template example",
"myvar": "Variable example",
}
layoutCustomersBase := template.Must(template.ParseFiles("templates/customers-base.html"))
layoutCustomersProjects := template.Must(layoutCustomersBase.ParseFiles("templates/customers-projects.html"))
// Or layoutCustomersProfile, if you are parsing in the '/customers/profile' handler.
err := layoutError.Execute(w, data)
请注意,您可以在执行customers-projects
模板时定义“ title”变量;它将在基本模板中使用。