Add currentUser template func

This commit is contained in:
Lucas Schumacher 2024-08-29 23:22:04 -04:00
parent 530672437c
commit c4e5d3575e
2 changed files with 15 additions and 2 deletions

View File

@ -16,12 +16,15 @@
<a class="text-base font-semibold hover:text-blue-100 pr-8" href="/faq">FAQ</a>
</div>
<div class="space-x-4">
{{if currentUser }}
<form action="/signout" method="post" class="inline pr-4">
{{csrfField}}
<button type="submit">Sign out</button>
</form>
{{else}}
<a href="/signin">Sign in</a>
<a href="/signup" clss="px-4 py-2 bg-blue-700 hover:bg-blue-600 rounded">Sign up</a>
{{end}}
</div>
</nav>
</header>

View File

@ -11,6 +11,8 @@ import (
"os"
"strings"
userctx "git.kealoha.me/lks/lenslocked/context"
"git.kealoha.me/lks/lenslocked/models"
"github.com/gorilla/csrf"
)
@ -28,6 +30,7 @@ func (t Template) Execute(w http.ResponseWriter, r *http.Request, data interface
tpl = tpl.Funcs(template.FuncMap{
"csrfField": func() template.HTML { return csrf.TemplateField(r) },
"currentUser": func() *models.User { return userctx.User(r.Context()) },
})
w.Header().Set("Content-Type", "text/html; charset=utf8")
@ -40,6 +43,7 @@ func (t Template) Execute(w http.ResponseWriter, r *http.Request, data interface
}
io.Copy(w, &buf)
}
func (t Template) TestTemplate(data interface{}) error {
var testWriter strings.Builder
tpl, err := t.htmlTpl.Clone()
@ -50,6 +54,9 @@ func (t Template) TestTemplate(data interface{}) error {
"csrfField": func() template.HTML {
return `<div class="hidden">STUB: PLACEHOLDER</div>`
},
"currentUser": func() *models.User {
return &models.User{ID: 0, Email: "a@a"}
},
})
return tpl.Execute(&testWriter, data)
}
@ -62,7 +69,10 @@ func FromFS(fs fs.FS, pattern ...string) (Template, error) {
tpl := template.New(pattern[0])
tpl = tpl.Funcs(template.FuncMap{
"csrfField": func() (template.HTML, error) {
return `<div class="hidden">STUB: PLACEHOLDER</div>`, fmt.Errorf("csrfField Not Implimented")
return "", fmt.Errorf("csrfField Not Implimented")
},
"currentUser": func() (*models.User, error) {
return nil, fmt.Errorf("currentUser Not Implimented")
},
})
tpl, err := tpl.ParseFS(fs, pattern...)