2

Suppose that I have tow text files (go templates):

child.tmpl

TEXT1 
Hello {{ . }}

top.tmpl

TEXT2
{{ template "child.tmpl" "argument"}}

the child.tmpl template is nested in top.tmpl

A typical program to parse them will be :

package main

import (
    "os"
    "text/template"
)

func main() {
    t := template.Must(template.ParseFiles("child.tmpl", "top.tmpl")
    t.ExecuteTemplate(os.Stdout, "top.tmpl", nil)
}

Is there any method the pass the template to be embedded in the top-level template as an argument using the {{ . }} notation ? something like {{ template {{.}} "argument" }}

  • More generally, what is the best way to define a layout template so I can use it like a top-level template to multiple child templates ?
4

1 回答 1

2

有两种公认的方法可以解决您的问题:

第一个涉及编写您自己的模板包含函数并将其注册为template.FuncMap您的模板通过template.Funcs.

另一种方法是在您的子模板中使用{{define xxx}}块。然后你可以有两个不同的文件来定义相同的模板:

  • 文件1.html:{{define body}}...{{end}}
  • 文件2.html:{{define body}}...{{end}}

根据您的需要解析正确的文件,并在您的模板中执行{{template body "argument"}}.

在我看来,第一种选择更灵活。

于 2013-09-23T06:28:41.600 回答