2017-03-06 96 views
2

我有三个连接的模板。 base.htmlmenu.htmlusers.html。但是当我执行这些模板时,我只能从base.html访问上下文的数据。无法从html /模板访问数据Golang

这里是我的处理程序:

func HandlerUser(res http.ResponseWriter, req *http.Request){ 
if req.Method == "GET" { 
    context := Context{Title: "Users"} 
    users,err:= GetUser(0) 
    context.Data=map[string]interface{}{ 
     "users": users, 
    } 
    fmt.Println(context.Data) 
    t,err := template.ParseFiles("public/base.html") 
    t,err = t.ParseFiles("public/menu.html") 
    t,err = t.ParseFiles("public/users.html") 
    err = t.Execute(res,context) 
    fmt.Println(err) 
} 
} 

这是我想说明在用户模板

{{ range $user := index .Data "users" }} 
<tr id="user-{{ .Id }}"> 
    <td id="cellId" >{{ $user.Id }}</td> 
    <td id="cellUserName" >{{ $user.UserName }}</td> 
</tr> 
{{ end }} 

注意什么:我可以访问"{{.Title}}"是在base.html模板中使用。

回答

1

首先,您应该检查Template.ParseFiles()方法返回的错误。你存储返回的错误,但你只在最后检查它(然后它被覆盖3次)。

接下来,永远不会分析请求处理程序中的模板,这太耗费时间和资源浪费。在启动时(或首次要求)做一次。详情请参阅It takes too much time when using "template" package to generate a dynamic web page to client in golang

接下来,您可以一次解析多个文件,只需枚举所有传递到Template.ParseFiles()函数(有一个方法和一个函数)。

知道Template.Execute()只执行一个(指定)模板。您有3 关联的模板,但只有"base.html"模板由您的代码执行。要执行一个特定的,请命名为模板,请使用Template.ExecuteTemplate()。详情请参阅Telling Golang which template to execute first

首先,您应该定义结构您的模板,决定哪些模板包含其他模板,并执行“包装器”模板(使用Template.ExecuteTemplate())。当你执行一个调用/包含另一个模板的模板时,你可以告诉你传递给它的执行的值(数据)。当您编写{{template "something" .}}时,这意味着您想要将当前指向的点值传递给名为"something"的模板的执行。阅读更多关于此:golang template engine pipelines

要了解有关模板关联和内部结构的更多信息,请阅读此答案:Go template name

所以在你的情况下,我会想象"base.html"是包装,外部模板,其中包括"menu.html""users.html"。所以"base.html"应该包含类似于这样的行:

{{template "menu.html" .}} 

{{template "users.html" .}} 

以上线路将调用,包括所提到的模板的结果,将数据传递给它们的执行传递给"base.html"(如果点没有变化)。

使用template.ParseFiles()功能(没有方法)这样的解析文件:

var t *template.Template 

func init() { 
    var err error 
    t, err = template.ParseFiles(
     "public/base.html", "public/menu.html", "public/users.html") 
    if err != nil { 
     panic(err) // handle error 
    } 
} 

并且处理函数中执行它是这样的:

err := t.ExecuteTemplate(w, "base.html", context) 
+0

谢谢回答。我没有把点管道传递数据 –