【问题标题】:In html/templates is there any way to have a constant header/footer across all pages?在 html/templates 中是否有任何方法可以在所有页面中使用恒定的页眉/页脚?
【发布时间】:2015-06-12 03:27:59
【问题描述】:

阅读docs 并不是特别有帮助,我想知道结构是否

{{header}}

   {{content that always changes}}

{{footer}}

可以通过 golang 实现。

【问题讨论】:

  • 如果您错过了,请阅读text/template 文档。
  • @TimCooper 我确实错过了:O
  • 如果您不想将任何数据传递给模板,这将起作用。否则,您可能会执行{{ template "header" . }} 之类的操作。
  • 这似乎不可能play.golang.org/p/C83SBwaZ_O
  • 您可以随时分别写出您的页眉、内容和页脚。例如:headerTPL.Execute(out, data); contentTPL.Execute(out, data); footerTPL.Execute(out, data).

标签: go go-html-template


【解决方案1】:

使用text/template

  1. 将其呈现到标准输出的代码

    t := template.Must(template.ParseFiles("main.tmpl", "head.tmpl", "foot.tmpl"))
    t.Execute(os.Stdout, nil)
    
  2. main.tmpl:

    {{template "header" .}}
    <p>main content</p>
    {{template "footer" .}}
    
  3. foot.tmpl:

    {{define "footer"}}
    <footer>This is the foot</footer>
    {{end}}
    
  4. head.tmpl:

    {{define "header"}}
    <header>This is the head</header>
    {{end}}
    

这将导致:

<header>This is the head</header>
<p>main content</p>
<footer>This is the foot</footer>

使用html/template 会非常相似。

【讨论】:

  • 请注意,您可以将多个模板放在具有多个 define ... end 块的同一源文件中。
  • 我不是 100%,但我认为您必须使用 if ... else 哪种会使水变得浑浊。我的直觉是这种逻辑应该在渲染模板的代码中,而不是模板本身。所以你可能有{{ .RenderedPageContent }} 而不是{{ template .Page . }}
猜你喜欢
  • 1970-01-01
  • 2022-12-18
  • 2012-01-25
  • 2011-11-09
  • 2019-10-01
  • 2012-04-26
  • 1970-01-01
  • 2013-09-18
  • 2016-04-30
相关资源
最近更新 更多