can you load a widget with parameters in a hamlet file in yesod?

316 views Asked by At

what is the best way to load html from a widget if your looping through a data set?

i.e. in a hamlet file

$forall Entity id val <- collection
    ^{myWidget (p1 val) (p2 val)}
1

There are 1 answers

1
Sibi On

Note that Hamlet template can embed only hamlet template. If you want to embed a widget, use whamlet.

Also, yes - you can pass parameters to a widget. An example stack script demonstrating the concept:

#!/usr/bin/env stack
{- stack
     --resolver lts-9.0
     --install-ghc
     runghc
     --package yesod-core
     --package yesod
     --package shakespeare
-}

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
{-# LANGUAGE TemplateHaskell   #-}
{-# LANGUAGE TypeFamilies      #-}
import           Yesod

data App = App
mkYesod "App" [parseRoutes|
/ HomeR GET
|]

instance Yesod App

data Person = Person { id :: Int, name :: String, email :: String } deriving (Show, Eq, Ord)

collections = [Person 1 "Sibi" "[email protected]", Person 2 "Michael" "[email protected]"]


whamlet1 :: Widget
whamlet1 = [whamlet| <p>hello
                   $forall Person _ pname pemail <- collections
                     ^{whamlet2 pname pemail}
           |]

whamlet2 :: String -> String -> Widget
whamlet2 pname pemail = [whamlet| <h1> #{pname} #{pemail} |]

getHomeR = defaultLayout $ do
    setTitle "My Page Title"
    toWidget [lucius| h1 { color: green; } |]
    whamlet1

main = warp 3000 App

The widgets chapter on Yesod book explains them more deeply.