We're going to write a very simple AJAX application. It will be a simple site with a few pages and a navbar; when you have Javascript, clicking on the links will load the pages via AJAX. Otherwise, it will use static HTML.
We're going to use jQuery for the Javascript, though anything would work just fine. Also, the AJAX responses will be served as JSON. Let's get started.
> {-# LANGUAGE TypeFamilies, QuasiQuotes, TemplateHaskell, MultiParamTypeClasses, OverloadedStrings #-} > import Yesod > import Yesod.Static > import Data.Text (Text, unpack) Like the blog example, we'll define some data first. > data Page = Page > { pageName :: Text > , pageSlug :: Text > , pageContent :: Text > } > loadPages :: IO [Page] > loadPages = return > [ Page "Page 1" "page-1" "My first page" > , Page "Page 2" "page-2" "My second page" > , Page "Page 3" "page-3" "My third page" > ] > data Ajax = Ajax > { ajaxPages :: [Page] > , ajaxStatic :: Static > } Next we'll generate a function for each file in our static folder. This way, we get a compiler warning when trying to using a file which does not exist. > staticFiles "static/yesod/ajax" Now the routes; we'll have a homepage, a pattern for the pages, and use a static subsite for the Javascript and CSS files. > mkYesod "Ajax" [parseRoutes| > / HomeR GET > /page/#Text PageR GET > /static StaticR Static ajaxStatic > |]That third line there is the syntax for a subsite: Static is the datatype for the subsite argument; siteStatic returns the site itself (parse, render and dispatch functions); and ajaxStatic gets the subsite argument from the master argument.
Now, we'll define the Yesod instance. We'll still use a dummy approot value, but we're also going to define a default layout.
> instance Yesod Ajax where > approot _ = "" > defaultLayout widget = do > Ajax pages _ <- getYesod > content <- widgetToPageContent widget > hamletToRepHtml [hamlet| > \ > > > >