Chapter 5. Widgets

One of the challenges in web development is that we have to coordinate three different client-side technologies: HTML, CSS, and JavaScript. Worse still, we have to place these components in different locations on the page: CSS in a <style> tag in the head, JavaScript in a <script> tag in the head, and HTML in the body. And never mind if you want to put your CSS and JavaScript in separate files!

In practice, this works out fairly nicely when building a single page, because we can separate our structure (HTML), style (CSS), and logic (JavaScript). But when we want to build modular pieces of code that can be easily composed, it can be a headache to coordinate all three pieces separately. Widgets are Yesod’s solution to the problem. They also help with the issue of including libraries, such as jQuery, one time only.

Our four template languages—Hamlet, Cassius, Lucius, and Julius—provide the raw tools for constructing our output. Widgets provide the glue that allows them to work together seamlessly.

Synopsis

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

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

getHomeR = defaultLayout $ do
    setTitle "My Page Title"
    toWidget [lucius| h1 { color: green; } |]
    addScriptRemote
     "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"
    toWidget
        [julius|
            $(function() {
                $("h1").click(function(){
                    alert ...

Get Developing Web Apps with Haskell and Yesod, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.