D
D
Dmitry Shnyrev2015-12-11 11:48:41
go
Dmitry Shnyrev, 2015-12-11 11:48:41

How to access shared data in template?

Hi all.
I understand that the question is Nubian and has been asked more than once during the existence of Go, but for some reason I can’t google a single normal and simple explanation.
I'm trying to make a simple web application in go.
I use gorilla (mux, context, session) and unrolled/render for template regdering.
In all examples, the data is passed to the template through a structure or a map that is passed to the render function - everything is clear here.
What to do with the data that I need on each page? What is an elegant way to access the same context in a template?
A typical example is the current user. How can I get it in template so that I don't explicitly pass it in the map with data for each template each time.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kirill, 2015-12-11
@dmnBrest

Write a function into which you pass the context and data for rendering, in it from the context "pull" what you always need, add them to the data that came in and shove it into the render, something like this:

func HTML(c *Context, name string, data map[string]interface{}) {

  if data == nil {

    data = make(map[string]interface{})
  }

  data["CurrentUser"] = c.Get("CurrentUser")

  render.HTML(c, name, data)
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question