I have a golang server using templ to display a home page and navbar with the ‘login’ button. I also have authentication with sessions, and want to know what is the best way to pass a different navbar to homepage based on if the user is logged in?
I have a ‘checkAuth’ middleware, and my initial thoughts were that all routes would just use this middleware and access the ‘isAuthenticated’ from the ctx and pass it to the handler. But it seems wrong to have to do this whenver i load a page?
route:
e.GET("/", handlers.HandleHome)
func HandleHome(c echo.Context) error {
return Render(c, home.Index(c.Get("isAuthenticated").(bool)))
}
middleware:
func checkAuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
session, _ := store.Get(c.Request(), "session")
isAuthenticated := session.Values["authenticated"] == true
if !isAuthenticated {
return c.Redirect(http.StatusUnauthorized, "/")
}
c.Set("isAuthenticated", isAuthenticated)
return next(c)
}
}
HTML:
home.tmpl
templ Index(isLoggedIn bool) {
@layouts.Base(isLoggedIn) {
base.tmpl
templ Base(isLoggedIn bool) {
@components.Navigation(isLoggedIn)
}
navigation.tmpl
templ Navigation(isLoggedIn bool) {
<nav>
if isLoggedIn {
<div>Welcome back!</div>
} else {
<input name="login" type="button" value="Log in"/>
}
</nav>
}
I solved this by using the context, which templ has access to when passed into the render function.
You can then access the context and any values within the template file itself.
I made sure that the login was passed into the context on every request using middleware.
https://templ.guide/syntax-and-usage/context/