在html/templates中,有没有办法在所有页面上都有一个固定的页眉/页脚?

huangapple go评论144阅读模式
英文:

In html/templates is there any way to have a constant header/footer across all pages?

问题

阅读文档并没有特别有帮助,我想知道是否可以用golang实现以下结构:

{{header}}

   {{content that always changes}}

{{footer}}
英文:

Reading the docs wasn't particularly helpful and I want to know if the structure

{{header}}

   {{content that always changes}}

{{footer}}

is achievable with golang.

答案1

得分: 2

使用text/template

  1. 将其渲染到标准输出的代码
t := template.Must(template.ParseFiles("main.tmpl", "head.tmpl", "foot.tmpl"))
t.Execute(os.Stdout, nil)
  1. main.tmpl:
{{template "header" .}}
<p>主要内容</p>
{{template "footer" .}}
  1. foot.tmpl:
{{define "footer"}}
<footer>这是页脚</footer>
{{end}}
  1. head.tmpl:
{{define "header"}}
<header>这是页头</header>
{{end}}

结果将会是:

<header>这是页头</header>
<p>主要内容</p>
<footer>这是页脚</footer>

使用html/template的方式非常类似。

英文:

Using text/template:

  1. Code to render it to Stdout

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

    {{template &quot;header&quot; .}}
    &lt;p&gt;main content&lt;/p&gt;
    {{template &quot;footer&quot; .}}
    
  3. foot.tmpl:

    {{define &quot;footer&quot;}}
    &lt;footer&gt;This is the foot&lt;/footer&gt;
    {{end}}
    
  4. head.tmpl:

    {{define &quot;header&quot;}}
    &lt;header&gt;This is the head&lt;/header&gt;
    {{end}}
    

This will result in:

&lt;header&gt;This is the head&lt;/header&gt;
&lt;p&gt;main content&lt;/p&gt;
&lt;footer&gt;This is the foot&lt;/footer&gt;

Using html/template will be extremely similar.

huangapple
  • 本文由 发表于 2015年6月12日 03:14:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/30789515.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定