如何在go中扩展模板? [英] How to extend a template in go?

查看:44
本文介绍了如何在go中扩展模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题所在:每个页面的 content 部分上有几个 article ,我想在下面插入一个 likebar 模板每篇文章.

Here is the problem: There are several articles on each page's content section and I'd like to insert a likebar template below each article.

所以 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".}} ,然后嵌套 {{template"likebar.tmpl".}}位于 {{define"content" 中,但失败:

How can I achieve this with html/template? I have tried to insert a {{template "iconbar" .}} in base.tmpl and then nested {{template "likebar.tmpl" .}} inside {{define "content" but it failed with:

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

Template File Error: html/template:base.tmpl:122:12: no such template "likebar.tmpl"

推荐答案

您只能包含/插入如果您有多个模板文件,请使用 template.ParseFiles() template.ParseGlob() 解析它们 all ,结果模板将具有所有已关联的模板,因此它们可以相互引用.

If you have multiple template files, use template.ParseFiles() or template.ParseGlob() to parse them all, and the result template will have all the templates, already associated, so they can refer to each other.

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

If you do use the above functions to parse your templates, then the reason why it can't find likebar.tmpl is because you are referring to it by an invalid name (e.g. missing folder name).

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

When parsing from string source, you may use the Template.Parse() method, which also associates nested templates to the top level template.

请参阅以下两个工作示例:

See these 2 working examples:

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}}`

输出(在游乐场上尝试):

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

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

这篇关于如何在go中扩展模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆