dogamak
dogamak

Reputation: 21

golang template.Execute and struct embedding

I have a little website project written go where you can store links, and I ran into a problem :

The website has many different pages which show different information so you need to pass template.Execute a different kind of a struct. But every page also needs info like username and tags, which are displayed in sidebar. I tried to make something like this instead of just making completely new struct type for each page.

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
}

But I get an error when I execute the template: "fp.tmpl" at <.Links>: can't evaluate field Links in type main.Page

The part of the template where the error occurs:

  {{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}}

And {{.Name}} doesn't work. (It's the function embedded from GeneralPage)

Upvotes: 1

Views: 2837

Answers (1)

nvcnvn
nvcnvn

Reputation: 5175

You're embeding the Page interface, but what you need is GeneralPage.
Maybe you can use a map[string]interface{} to store your data (and then check if not-nil in your template), it easier.
But you can share the main layout and just change the detail (like a master page).
Look at http://golang.org/pkg/text/template/#example_Template_share

Upvotes: 1

Related Questions