How To Make Go template to use Global Variables

1,997 views
Skip to first unread message

Felix Sun

unread,
Jun 27, 2012, 5:14:00 AM6/27/12
to golan...@googlegroups.com
Say I have 3 templates:

1. index.tpl
2. _post.tpl
3. _comment.tpl

and the data structure is like:

type IndexData struct {
Posts []*Post
}

type Post struct {
Comments []*Comment
CreatedAt time.Time
}

type Comment struct {
CreatedAt time.Time
}

Note that I render a collection of Posts inside index.tpl like this:

{{range .Posts}}
{{template "post" .}}
{{end}}

and Inside _post.tpl I render a collection of comments:

{{range .Comments}}
{{template "comment" .}
{{end}}

So the problem is, I need to show the Creation date of the posts and
the comments according to Logged in user's Timezone, different user
seems different format for the same actual time value. The template
will be like this:

{{.CreatedAtInTimezone $loggedInUser.Timezone }}

And It doesn't feel right If I put the LoggedInUser's Timezone info
object into all IndexData and Post and Comment struct and set the
value in Loop before rendering the templates,
So how can I get the LoggedInUser info inside the 3 templates?

André Paquet

unread,
Jun 27, 2012, 9:41:23 AM6/27/12
to golan...@googlegroups.com
How about something like this [1] ? 

Kyle Lemons

unread,
Jun 27, 2012, 3:34:05 PM6/27/12
to Felix Sun, golan...@googlegroups.com
I have a Common type into which I put data that should be available to all templates, and I embed this into the (usually anonymous) data structures that I use for template execution.
Reply all
Reply to author
Forward
0 new messages