Last active
December 4, 2019 02:46
-
-
Save jessta/9fd6ffa6959a32f4d8f5670d365a5c2a to your computer and use it in GitHub Desktop.
Simple Elm SPA example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (Model, Msg(..), about, home, main, routes, update, view) | |
import Browser | |
import Browser.Navigation as Nav | |
import Html exposing (..) | |
import Html.Attributes exposing (..) | |
import Url | |
import Dict | |
main : Program () Model Msg | |
main = | |
Browser.application | |
{ init = \flags url key -> ( Model key url, Cmd.none ) | |
, view = view | |
, update = update | |
, subscriptions = always Sub.none | |
, onUrlChange = UrlChanged | |
, onUrlRequest = LinkClicked | |
} | |
type alias Model = | |
{ key : Nav.Key | |
, url : Url.Url | |
} | |
routes = | |
Dict.fromList | |
[ ( "/" | |
, home | |
) | |
, ( "/about" | |
, about | |
) | |
] | |
type Msg | |
= LinkClicked Browser.UrlRequest | |
| UrlChanged Url.Url | |
update : Msg -> Model -> ( Model, Cmd Msg ) | |
update msg model = | |
case msg of | |
LinkClicked urlRequest -> | |
case urlRequest of | |
Browser.Internal url -> | |
( model, Nav.pushUrl model.key (Url.toString url) ) | |
Browser.External href -> | |
( model, Nav.load href ) | |
UrlChanged url -> | |
( { model | url = url } | |
, Cmd.none | |
) | |
view : Model -> Browser.Document Msg | |
view model = | |
{ title = "Simple SPA example" | |
, body = | |
[ case model.url.path of | |
"/" -> home | |
"/about" -> about | |
_ -> notFound | |
] | |
} | |
home : Html msg | |
home = | |
text "The home page" | |
about : Html msg | |
about = | |
text "the about page" | |
notFound : Html msg | |
notFound = text "no page was found" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment