Karlom
Karlom

Reputation: 14874

How to access session variable inside a template range?

I want to add an Edit button which appear only for moderators:

{{range $n := .articles}}
   <p>{{$n.Content}} </p>
   {{ if .is_mod}}
      <button> Edit </button>
   {{end}}
{{end }}

I have already set is_mod as a boolean variable in session and passed it to template. However, it is not a field in the Article struct, so, I get this error:

executing "content" at <.is_mod>: is_mod is not a field of struct type model.Article.

One obvious solution is to make a new struct in the controller which includes a IsMod field and pass that to template, but that is messy and inefficient so I'd rather avoid it if possible and looking for a more elegant solution.

Upvotes: 1

Views: 565

Answers (2)

Shakhawat Hossain
Shakhawat Hossain

Reputation: 78

This works for me.

c.HTML(http.StatusOK, "index.html", gin.H {
  "posts": posts,
  "some_data": "Home page posts",
})

Upvotes: 0

Bhavana
Bhavana

Reputation: 1054

You need to pass session variable to the template. I didn't tried it, but you can try something like this:

c.HMTL(http.StatusOK, "template_name", gin.H {
  "articles": articles,
  "is_mod": is_mod,
})

The above syntax is for gin-gonic/gin framework. .

Upvotes: 1

Related Questions