golang template.Execute和struct embedding

时间:2013-12-17 17:34:44

标签: templates go

我写了一个小网站项目,你可以存储链接,我遇到了一个问题:

该网站有许多不同的页面,显示不同的信息,因此您需要传递模板。执行不同类型的结构。但每个页面还需要用户名和标签等信息,这些信息显示在侧栏中。我尝试制作这样的东西,而不是为每个页面制作全新的结构类型。

http://play.golang.org/p/VNfD6i8p_N

type Page interface {
    Name() string
}

type GeneralPage struct {
    PageName string
}

func (s GeneralPage) Name() string {
    return s.PageName
}

type PageRoot struct {
    Page
    Tags       []string
    IsLoggedIn bool
    Username   string
}

type ListPage struct {
    Page
    Links     []Link
    IsTagPage bool
    Tag       string
}

type GalleryPage struct {
    Page
    Image    Link
    Next     int
    Previous int
}

但是当我执行模板时遇到错误:"fp.tmpl" at <.Links>: can't evaluate field Links in type main.Page

发生错误的模板部分:

  {{with .Page}}
  {{range .Links}}
  <tr>
    <td>{{if .IsImage}}<img src="{{.Url}}" />{{end}}</td>
    <td>{{.Name}}</td>
    <td>{{.Url}}</td>
    <td>{{.TagsString}}</td>
  </tr>
  {{end}}
  {{end}}

并且{{.Name}}不起作用。 (这是从GeneralPage嵌入的功能)

1 个答案:

答案 0 :(得分:1)

您正在嵌入 Page界面,但您需要的是 GeneralPage
也许您可以使用map [string] interface {}来存储数据(然后检查模板中是否为nil),这样更容易。
但您可以共享主要布局,只需更改细节(如母版页) 看http://golang.org/pkg/text/template/#example_Template_share

相关问题