在 html/templates 中,有什么方法可以在所有页面上设置常量 header/footer 吗?

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

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

{{header}}

   {{content that always changes}}

{{footer}}

可以用 golang 实现。

使用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会非常相似。