douwei3172 2018-06-13 16:46
浏览 12
已采纳

在Go中解析多个模板

I'm trying to figure out how to go about loading multiple templates in Go when a lot of them have a similar....base, you could say?

Currently, I've got the following two templates I'm loading in a sample application I'm working on:

homeTemplate, err = template.ParseFiles(
    "views/layout/base.gohtml",
    "views/layout/menu.html",
    "views/layout/footer.gohtml",
    "views/home.gohtml")
if err != nil {
    panic(err)
}

contactTemplate, err = template.ParseFiles(
    "views/layout/base.gohtml",
    "views/layout/menu.html",
    "views/layout/footer.gohtml",
    "views/contact.gohtml")
if err != nil {
    panic(err)
}

My question is the following:

Is there a way to set this up in such a way that I can store the first three entries in each list of templates in a variable and then just append the final inclusion at the end so I can shorten the amount of code and simplify things?

Am I tackling this whole thing wrong? I read somewhere about using a setup that incorporated a template["name"] syntax and then rendering from that, maybe I just need to load the base templates before the rest of this stuff, since they're more of less for layout stuff, and they probably don't need to be part of the above variables?

  • 写回答

2条回答 默认 最新

  • douke1942 2018-06-13 17:33
    关注

    https://golang.org/pkg/html/template/#Template.Clone

    Clone can be used to prepare common templates and use them with variant definitions for other templates by adding the variants after the clone is made.

    baseTemplate, err = template.ParseFiles(
        "views/layout/base.gohtml",
        "views/layout/menu.html",
        "views/layout/footer.gohtml")
    if err != nil {
        panic(err)
    }
    
    homeTemplate, err = template.Must(baseTemplate.Clone()).ParseFiles("views/home.gohtml")
    if err != nil {
        panic(err)
    }
    
    contactTemplate, err = template.Must(baseTemplate.Clone()).ParseFiles("views/contact.gohtml")
    if err != nil {
        panic(err)
    }
    

    https://play.golang.org/p/q9ox01W8U00

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改