Answer the question
In order to leave comments, you need to log in
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)
}
{{ 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 }}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question