W
W
wargych2018-02-13 13:57:32
go
wargych, 2018-02-13 13:57:32

How to pass a variable to a template?

There is a handler:

func IndexHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("templates/index.html", "templates/header.html", "templates/footer.html")
if err != nil {
fmt.Fprintf(w, err.Error())
}
c := ReadCookie(r)
IsAuthorized, Username := IsAuthorized(c)
fmt.Println(IsAuthorized, Username)
postCollection := GVDB.PostCollection // object MongoDB
PostDocuments := []documents.PostDocument{}
postCollection.Find(nil).All(&PostDocuments)
Posts := []models.Post{}
for _, doc := range PostDocuments {
Post := models.Post{doc. Id, doc.Title, doc.Content}
Posts = append(Posts, Post)
}
t.ExecuteTemplate(w, "index", Posts)
}

There is a template:
{{ define "index" }}

{{ template "header"}}
{{ range $value := . }}
<div class="row">
  <div class="col-xs-2">
  </div>
  <div class="col-xs-8">
    {{if $.IsAuthorized}}
    <h1><a href="/edit?id={{$value.Id}}">{{ $value.Title }}</a></h1>
    {{else}}
    <h1><a href="/view?id={{$value.Id}}">{{ $value.Title }}</a></h1>
    {{end}}
  </div>
  <div class="col-xs-2">
  </div>
</div>
<div class="row">
  <div class="col-xs-2">
  </div>
  <div class="col-xs-8">
    {{ $value.Content }}
  </div>
  <div class="col-xs-2">
  </div>
</div>
{{ end }}

{{ template "footer" }}

{{ end }}

In this form, the check for IzAuthorized does not pass. How to do it right? How can you pass an authorization check to a template in general, and what can you read about working with templates? I looked at the official documentation and the article: https://github.com/astaxie/build-web-application-w... , but everything I tried did not work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Tsvetkov, 2018-02-13
@wargych

You need to pass IsAuthorized to the template, something like this
https://play.golang.org/p/ytzbaUnvKMH

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question