Chapter 17. Creating a Subsite

How many sites provide authentication systems? Or need to provide create, read, update, and delete (CRUD) management of some objects? Or a blog? Or a wiki?

The theme here is that many websites include common components that can be reused throughout multiple sites. However, it is often quite difficult to get code to be modular enough to be truly plug and play: a component will require hooks into the routing system, usually for multiple routes, and will need some way of sharing styling information with the master site.

In Yesod, the solution is subsites. A subsite is a collection of routes and their handlers that can be easily inserted into a master site.The use of typeclasses makes it easy to ensure that the master site provides certain capabilities, and to access the default site layout. And with type-safe URLs, it’s easy to link from the master site to subsites.

Hello, World

Perhaps the trickiest part of writing subsites is getting started. Let’s dive in with a simple Hello, World subsite. We need to create one module to contain our subsite’s data types, another for the subsite’s dispatch code, and then a final module for an application that uses the subsite.

Note

The reason for the breakdown between the data and dispatch code is due to the GHC stage restriction. This requirement makes smaller demos a bit more verbose, but in practice, this splitting up into multiple modules is a good practice to adhere to.

-- @HelloSub/Data.hs
{-# LANGUAGE QuasiQuotes ...

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.