Skip to content

Commit

Permalink
Add renderHtmlPartial function
Browse files Browse the repository at this point in the history
  • Loading branch information
kodeFant committed Oct 5, 2023
1 parent 4f1c9fb commit aa4f2c2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Guide/htmx-and-hyperscript.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ data CounterController
deriving (Eq, Show, Data)
```

Instead of using the `render` function, htmx routes are better used with `respondHtml` to avoid the layout being shipped as part of the response. The same function can be used for initializing the view as well as upating.
Instead of using the `render` function, htmx routes are better used with `renderHtmlPartial` to avoid the layout being shipped as part of the response. The same function can be used for initializing the view as well as upating.

```haskell
module Web.Controller.Counter where
Expand All @@ -83,12 +83,12 @@ instance Controller CounterController where
action IncrementCountAction{counterId} = do
counter <- fetch counterId
updatedCounter <- counter |> incrementField #count |> updateRecord
respondHtml $ counterView updatedCounter
renderHtmlPartial $ counterView updatedCounter

action DecrementCountAction{counterId} = do
counter <- fetch counterId
updatedCounter <- counter |> decrementField #count |> updateRecord
respondHtml $ counterView updatedCounter
renderHtmlPartial $ counterView updatedCounter
```

We define the `CounterView` like this, separating the `counterView` function into a function that can be used be the initial view as well as the updater routes (`IncrementCountAction` and `DecrementCountAction`).
Expand Down
10 changes: 10 additions & 0 deletions IHP/Controller/Render.hs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ renderHtml !view = do
pure boundHtml
{-# INLINABLE renderHtml #-}

-- | Renders an HTML partial without the layout.
-- This is useful when you want to render a view inside another view, for example with htmx.
renderHtmlPartial :: (?context :: ControllerContext) => Html -> IO ()
renderHtmlPartial htmlPartial = do
frozenContext <- Context.freeze ?context
let ?context = frozenContext
let boundHtml = let ?context = frozenContext in htmlPartial
respondHtml boundHtml
{-# INLINABLE renderHtmlPartial #-}

renderFile :: (?context :: ControllerContext) => String -> ByteString -> IO ()
renderFile filePath contentType = respondAndExit $ responseFile status200 [(hContentType, contentType)] filePath Nothing
{-# INLINABLE renderFile #-}
Expand Down

0 comments on commit aa4f2c2

Please sign in to comment.