2

不知道如何正确命名。

有没有办法编写一个主模板和许多片段并根据 URL 用户请求注入所需的片段。假设我有/customers/profile/customers/projects。我想用 2 个{{ define "profile" }}{{ define "projects" }}片段编写一个主要的customer.html模板文件和一个customer-includes.html文件。然后我想要 2 个处理程序来处理/customers/profile/customers/projects并执行customer.html模板。但是,当用户转到 URL /customers/profile我想注入主模板{{ template "profile" 。}}如果他去/customers/projects我想注入{{ template "projects" 。}}。做这个的最好方式是什么?我假设我需要在那里使用某种 {{ if / else }} 。如下例所示。但是mby有更好的方法。

        {{ if ( eq .Section "customer-profile") }} // Could be replaced with Page ID
            {{ template "profile" . }}
            {{ else }}
            {{ template "projects" . }}
        {{ end}}
4

1 回答 1

4

您可以为此使用模板块。

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”变量;它将在基本模板中使用。

于 2018-07-09T22:08:52.897 回答