gpt4 book ai didi

go - 根据请求的 URL 在主模板中执行模板片段

转载 作者:IT王子 更新时间:2023-10-29 01:56:57 26 4
gpt4 key购买 nike

不确定如何正确命名。

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

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

最佳答案

您可以为此使用模板 block 。

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

关于go - 根据请求的 URL 在主模板中执行模板片段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51248479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com