代码之家  ›  专栏  ›  技术社区  ›  Dzintars

基于请求的url在主模板中执行模板片段

  •  1
  • Dzintars  · 技术社区  · 6 年前

    不知道如何正确命名。

    是否有任何方法可以编写一个主模板和多个片段,并根据url用户请求注入所需片段。 假设我有 /客户/简介 /客户/项目 是的。我想写一首歌 客户.html 模板文件和一个 customer-includes.html网站 用2归档 {{定义“配置文件”} {{定义“项目”} 碎片。 那我要有两个处理程序来处理 /客户/简介 /客户/项目 执行 客户.html 模板。 但是,当用户转到url时 /客户/简介 我想注入主模板 {{模板“配置文件”。} 如果他去 /客户/项目 我想注射 {{模板“项目”。}} 是的。 最好的方法是什么? 我想我需要在那里使用某种{{if/else}。如下例。但有更好的办法。

            {{ if ( eq .Section "customer-profile") }} // Could be replaced with Page ID
                {{ template "profile" . }}
                {{ else }}
                {{ template "projects" . }}
            {{ end}}
    
    1 回复  |  直到 6 年前
        1
  •  3
  •   Arthur Ruckman    6 年前

    可以为此使用模板块。

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