2012-09-18 34 views
4

在做ExecuteTemplate时,我看到所有使用&whateversruct{Title: "title info", Body: "body info"}的示例都将数据发送到模板以替换信息。我想知道是否可能不需要在我的处理函数之外创建一个结构,因为我拥有的每个处理函数都不会具有相同的Title,Body。能够发送替换模板信息的地图会很好。任何想法或想法?全局模板数据

目前 - 松散的书面

type Info struct { 
    Title string 
    Body string 
} 

func View(w http.ResponseWriter) { 
    temp.ExecuteTemplate(w, temp.Name(), &Info{Title: "title", Body: "body"}) 
} 

似乎只是创建结构是不必要的。对于您创建的每个函数,结构都不相同。所以你将不得不为每个函数创建一个结构(我知道的)。

回答

10

该结构只是一个例子。您也可以从外部传递结构,或者您可以按照您的建议使用地图。结构很好,因为结构的类型可以记录模板期望的字段,但这不是必需的。

所有这些都应该工作:

func View(w http.ResponseWriter, info Info) { 
    temp.ExecuteTemplate(w, temp.Name(), &info) 
} 

func View(w http.ResponseWriter, info *Info) { 
    temp.ExecuteTemplate(w, temp.Name(), info) 
} 

func View(w http.ResponseWriter, info map[string]interface{}) { 
    temp.ExecuteTemplate(w, temp.Name(), info) 
} 
1

你是完全正确的凯文!我更喜欢这个。谢谢!!!

func View(w http.ResponseWriter) { 
    info := make(map[string]string) 
    info["Title"] = "About Page" 
    info["Body"] = "Body Info" 
    temp.ExecuteTemplate(w, temp.Name(), info) 
} 
14

为了增强凯文的回答是:匿名结构将产生许多相同的行为:

func View(w http.ResponseWriter) { 
    data := struct { 
     Title string 
     Body string 
    } { 
     "About page", 
     "Body info", 
    } 

    temp.ExecuteTemplate(w, temp.Name(), &data) 
} 
6

应用模板的结构与到地图之间的一个重要区别:与地图,你可以在您的模板中引用地图中不存在的引用;该模板将执行时不会出现错误,并且引用将仅为空。如果您针对某个结构进行处理并对结构中不存在的内容进行引用,则模板执行将返回一个错误。

引用地图中不存在的项目可能很有用。请考虑下列示例webapp中的views.go中的menu.html和getPage()函数:https://bitbucket.org/jzs/sketchground/src。通过使用菜单的地图,活动菜单项很容易突出显示。

这种差异的一个简单的例子:

package main 

import (
    "fmt" 
    "html/template" 
    "os" 
) 

type Inventory struct { 
    Material string 
    Count uint 
} 

func main() { 
    // prep the template 
    tmpl, err := template.New("test").Parse("{{.Count}} items are made of {{.Material}} - {{.Foo}}\n") 
    if err != nil { 
     panic(err) 
    } 

    // map first 
    sweaterMap := map[string]string{"Count": "17", "Material": "wool"} 
    err = tmpl.Execute(os.Stdout, sweaterMap) 
    if err != nil { 
     fmt.Println("Error!") 
     fmt.Println(err) 
    } 

    // struct second 
    sweaters := Inventory{"wool", 17} 
    err = tmpl.Execute(os.Stdout, sweaters) 
    if err != nil { 
     fmt.Println("Error!") 
     fmt.Println(err) 
    } 
}