How to query database inside an view? #600
-
I'm trying to dynamically render links inside a navigation bar using categories from the database. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
You could write a controller helper that stores the navigation items inside the controller context and then hook it into the fetchNavigation = do
categories :: [Category] <- query @Category |> fetch
putContext categories
-- Inside the controller file
instance Controller MyController where
beforeAction = do
fetchNavigation Now access this inside the view like this:
|
Beta Was this translation helpful? Give feedback.
-
@mpscholten You might have guessed that my next question is: Could we have a controller that is initialized before every controller? |
Beta Was this translation helpful? Give feedback.
-
Here is an example of adding
module Web.FrontController where
import IHP.ControllerPrelude
import IHP.LoginSupport.Middleware
import IHP.RouterPrelude
import Web.Controller.Articles
import Web.Controller.Categories
import Web.Controller.Prelude
import Web.Controller.Sessions
import Web.Controller.Static
import Web.Controller.Users
import Web.View.Layout
-- Context Used Inside The Navigation Bar
fetchCategories :: (?modelContext :: ModelContext, ?context :: ControllerContext) => IO ()
fetchCategories = do
categories :: [Category] <- query @Category |> fetch
putContext categories
instance FrontController WebApplication where
controllers =
[ startPage WelcomeAction,
parseRoute @UsersController,
parseRoute @SessionsController,
parseRoute @ArticlesController,
parseRoute @CategoriesController
-- Generator Marker
]
instance InitControllerContext WebApplication where
initContext = do
setLayout defaultLayout
initAuthentication @User
fetchCategories
navigation :: Html
navigation =
[hsx|
<nav class="flex h-20 pl-6 pr-6 fixed w-full bg-white z-10">
<div class="flex-1 self-center flex justify-center">
{categoriesWithLinks}
</div>
</nav>
|]
where
categoriesWithLinks :: Html
categoriesWithLinks =
[hsx|{forEach categories renderCategory}|]
where
categories :: [Category]
categories = fromFrozenContext @[Category]
categoryPath :: Category -> Text
categoryPath category =
let categoryId = Nothing
slug = Just (get #slug category)
in pathTo ShowCategoryAction {..}
renderCategory :: Category -> Html
renderCategory category =
[hsx|<a href={categoryPath category}>{get #name category}</a>|] |
Beta Was this translation helpful? Give feedback.
You could write a controller helper that stores the navigation items inside the controller context and then hook it into the
beforeAction
like this:Now access this inside the view like this: