Search code examples
haskellhaskell-snap-frameworkheist

Working with routes and html (Heist) in Snap


I have templates (*.tpl) in my-snap-app/snaplets/heist/templates (main.tpl, page1.tpl, page2.tpl, page3.tpl). And here's my Main.hs:

import Snap.Http.Server
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Heist
import Snap.Util.FileServe
import Snap.Util.GZip
import Heist.Interpreted
import Heist

--.......

data App = App { _heist :: Snaplet (Heist App) }
makeLenses ''App

instance HasHeist App where 
  heistLens = subSnaplet heist

How can I:

a) Make all the templates available in my web app? Meaning, I want to be able to access page1.tpl, page2.tpl, page3.tpl on localhost://page1, localhost://page2, localhost://page3. Should I necessarily add a route for each page or can I add a route to make them accessible all at once?

2) main.tpl is a main template (layout). How can I make page[123] use main.tpl as a master layout template?


Solution

  • The Heist snaplet has a function serveHeist that acts a lot like serveDirectory. That will serve all of the templates in templates/ at routes. The haddocks have some more details about, e.g. hiding certain templates that don't make sense on their own.

    For composing different templates together, think of templates like functions - you can apply them to other templates, and the result is itself a template. These things all happen in Heist itself, rather than in snap.

    The <apply> tag performs the function application. The argument is the content inside of <apply>, for example, in page1.tpl:

    <apply>
      <h1>I'm a function parameter</h1>
    </apply>
    

    The function being applied is main.tpl, and the parameter is <apply-content>:

    <html><head></head>
      <body>
        <h1>Main template.</h1>
        <apply-content/>
      </body>
    </html>
    

    The use of <apply> and <apply-content> perform the function application and compute a full page, which would be available at the /page1 route.

    There is a lot more explanation in the Heist Tutorial. I wonder if the function-application analogy is useful for remembering more of the heist API.