Chapter 7. Routing and Handlers

If we look at Yesod as a model-view-controller framework, routing and handlers make up the controller. For contrast, let’s describe two other routing approaches used in other web development environments:

  • Dispatch based on filename. This is how PHP and ASP work, for example.

  • Have a centralized routing function that parses routes based on regular expressions. Django and Rails follow this approach.

Yesod is closer in principle to the latter technique. Even so, there are significant differences. Instead of using regular expressions, Yesod matches on pieces of a route. Instead of having a one-way route-to-handler mapping, Yesod has an intermediate data type (called the route or type-safe URL data type) and creates two-way conversion functions.

Coding this more advanced system manually is tedious and error prone. Therefore, Yesod defines a domain-specific language (DSL) for specifying routes, and provides Template Haskell functions to convert this DSL to Haskell code. This chapter will explain the syntax of the routing declarations, give you a glimpse of what code is generated for you, and explain the interaction between routing and handler functions.

Route Syntax

Instead of trying to shoehorn route declarations into an existing syntax, Yesod’s approach is to use a simplified syntax designed just for routes. This has the advantage of making the code not only easy to write, but simple enough that someone with no Yesod experience can read and understand ...

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.