【问题标题】:How to extend a template in go?如何在go中扩展模板?
【发布时间】:2016-11-21 06:51:58
【问题描述】:

问题出在:每个页面的content 部分有几个articles,我想在每篇文章下方插入一个likebar 模板。

所以base.tmpl 就像:

<html>
  <head>    
    {{template "head.tmpl" .}}
  </head>
  <body>    
    {{template "content.tmpl" .}}   
   </body>
</html>

article.tmpl 我想要:

    {{define "content"}}    
          <div>article 1 
             {{template "likebar.tmpl" .}} 
          </div> 
          <div>article 2
             {{template "likebar.tmpl" .}} 
         </div>
       ... //these divs are generated dynamically
    {{end}}

如何使用html/template 实现这一目标? 我试图在base.tmpl 中插入一个{{template "iconbar" .}},然后在{{define "content" 中嵌套{{template "likebar.tmpl" .}},但它失败了:

模板文件错误:html/template:base.tmpl:122:12:没有这样的模板 "likebar.tmpl"

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    您只能包含/插入associated templates

    如果你有多个模板文件,使用template.ParseFiles()template.ParseGlob()来解析它们all,结果模板将有所有模板,已经关联,所以它们可以互相引用.

    如果您确实使用上述函数来解析您的模板,那么它找不到likebar.tmpl 的原因是因为您使用无效名称(例如缺少文件夹名称)引用它。

    string 源解析时,您可以使用Template.Parse() 方法,该方法还将嵌套模板与顶级模板相关联。

    查看以下 2 个工作示例:

    func main() {
        t := template.Must(template.New("").Parse(templ1))
        if err := t.Execute(os.Stdout, nil); err != nil {
            panic(err)
        }
    
        t2 := template.Must(template.New("").Parse(templ2))
        template.Must(t2.Parse(templ2Like))
        if err := t2.Execute(os.Stdout, nil); err != nil {
            panic(err)
        }
    }
    
    const templ1 = `Base template #1
    And included one: {{template "likebar"}}
    {{define "likebar"}}I'm likebar #1.{{end}}
    `
    
    const templ2 = `Base template #2
    And included one: {{template "likebar"}}
    `
    
    const templ2Like = `{{define "likebar"}}I'm likebar #2.{{end}}`
    

    输出(在Go Playground上试试):

    Base template #1
    And included one: I'm likebar #1.
    
    Base template #2
    And included one: I'm likebar #2.
    

    【讨论】:

      猜你喜欢
      • 2011-07-16
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 2023-01-25
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多