This page covers Tutorial v2. Elm 0.18.
Routing introduction
Let's add a routing to our application. We will be using the Elm Navigation package and UrlParser.
- Navigation provides the means to change the browser location and respond to changes
- UrlParser provides route matchers
First install the packages:
elm-package install elm-lang/navigation
elm-package install evancz/url-parser
Navigation
is a library that wraps Html.program
. It has all the functionality of Html.program
plus some extra things:
- Listens for location changes on the browser
- Triggers a message when the location changes
- Provides ways of changing the browser location
Flow
Here are a couple of diagrams to understand how routing will work.
Initial render
- (1) When the page first loads the
Navigation
module will fetch the currentLocation
and send it to the applicationinit
function. - (2) In
init
we parse this location and get a matchingRoute
. - (3, 4) We then store this matched
Route
in our initial model and return this model toNavigation
. - (5, 6)
Navigation
then renders the view by sending this initial model.
When the location changes
- (1) When the browser location changes the Navigation library receives an event
- (2) A
OnLocationChange
message is sent to ourupdate
function. This message will contain the newLocation
. - (3, 4) In
update
we parse theLocation
and return the matchingRoute
. - (5) From
update
we return the updated model which contains the updateRoute
. - (6, 7) Navigation then renders the application as normal