How would you create your own default layout in Yesod?

Viewed 77

I'm a C# back end developer trying to learn web dev with haskell and Yesod, so please bear with me.

My question is, what is the convention regarding creating your own default layout. Should you create it dynamically, in code, or change the markup?

As I understand it, it's meant for consistency throughout your web app, at least for the parts that use the default layout. So it would typically be something static that stays the same in runtime for every part that uses it, until you wish to change it once, and have it impact every part that uses it. No need to generate the default layout with every page that loads.

Many thanks.

1 Answers

It's a bit of both.

If you use the Yesod scaffolding, then the example handler for the home page uses a function defaultLayout defined as follows:

defaultLayout :: Widget -> Handler Html
defaultLayout widget = do
    master <- getYesod
    mmsg <- getMessage

    muser <- maybeAuthPair
    mcurrentRoute <- getCurrentRoute

    -- Get the breadcrumbs, as defined in the YesodBreadcrumbs instance.
    (title, parents) <- breadcrumbs

    -- Define the menu items of the header.
    ...

    pc <- widgetToPageContent $ do
        addStylesheet $ StaticR css_bootstrap_css
        $(widgetFile "default-layout")
    withUrlRenderer $(hamletFile "templates/default-layout-wrapper.hamlet")

This sets up some dynamic information (any pending "message"? user authenticated?) and then renders the page (i.e., the Widget argument to defaultLayout) using two static Hamlet templates in the templates directory:

default-layout-wrapper.hamlet
default-layout.hamlet

The first is the site-wide <html> element template, except for the contents of the <body> which are placed in the second template. These are separated for some technical reasons.

So, the default layout is the result of a dyanmic defaultLayout function that uses static Hamlet templates.

Related