dqwh2717 2018-01-30 14:56
浏览 36

转到模板-嵌套模板

I have several go templates. The below examples are oversimplified, but it states my idea correctly. For example, I have

{{ define "div-block" }}
   <div style="display:block">
         .....
   </div>
{{ end }}

Now I want to transfer any other template inside div-block when using it, so that I could put anything inside div. E.g:

{{ template "div-block" . }}
    {{ template "header" }}
{{ end }}

{{ template "div-block" . }}
    <ul>
       <li>1</li>
    </ul>
{{ end }}

Where "header" is some other template.

Which is the the right way to do this with go template? Is it possible to do it with custom function? Is it possible to make custom actions in go template? (actions can have end statement and therefore the body, while functions are not)

  • 写回答

1条回答 默认 最新

  • dongzhiji0814 2018-01-30 18:05
    关注

    You can use nested template in go template.

    divBlock := `<div>Hello div
                    {{block "header" .}} {{.}} {{end}}
                 </div>`
    header := `<header>Hello Header</header>`
    
    divTempl, err := template.New("master").Parse(divBlock)
    if err != nil {
        log.Fatal(err)
    }
    if err := divTempl.Execute(os.Stdout, header); err != nil {
        log.Fatal(err)
    }
    

    Go-playground link: https://play.golang.org/p/K36l3bn5753

    Or

    You can use if statement. Check whether there is some template, then append, otherwise empty.

    const (
        divBlock = `<div style="display:block">
                     .....
                {{if "injectedTmpl"}}{{.}}{{end}}
               </div>`
    )   
    injectedTmpl := `<header>Hello Header</header>`
    
    divTmpl, err := template.New("div").Parse(divBlock)
    if err != nil {
        log.Fatal(err)
    }
    if err := divTmpl.Execute(os.Stdout, injectedTmpl); err != nil {
        log.Fatal(err)
    }
    

    Go-playground link: https://play.golang.org/p/pZaqXtCHHAL

    评论

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程