各施設の個別ページを作るため、まずは施設名のところをリンクにし、そこをクリックした時に/#facilities/施設ID
へページ遷移するようにします。
src/Routing.elmの作成・編集
施設個別ページ用のパスを設定します。後でこのファイルにルーティングのメソッドも書いて行きます。
module Routing exposing (..)
import Models exposing (FacilityId)
facilitiesPath : String
facilitiesPath =
"#facilities"
facilityPath : FacilityId -> String
facilityPath facilityId =
"#facilities/" ++ facilityId
src/Facilities/List.elmの編集
施設個別ページへ飛ぶためのリンクを作ります。施設名をリンクにし、施設IDをパスにします。全部載せていますが、変更箇所は、4行目と8行目のインポートと、62行目と70行目以下のみです。
module Facilities.List exposing (..)
import Html exposing (..)
import Html.Attributes exposing (href)
import Models exposing (Facility)
import Msgs exposing (Msg)
import RemoteData exposing (WebData)
import Routing exposing (facilityPath)
view : WebData (List Facility) -> Html Msg
view response =
div []
[ nav
, maybeList response
]
nav : Html Msg
nav =
div []
[ div [] [ text "施設一覧" ] ]
maybeList : WebData (List Facility) -> Html Msg
maybeList response =
case response of
RemoteData.NotAsked ->
text ""
RemoteData.Loading ->
text "Loading..."
RemoteData.Success facilities ->
list facilities
RemoteData.Failure error ->
text (toString error)
list : List Facility -> Html Msg
list facilities =
div []
[ table []
[ thead []
[ tr []
[ th [] [ text "Id" ]
, th [] [ text "Name" ]
, th [] [ text "Opening" ]
, th [] [ text "Address" ]
, th [] [ text "Postal code" ]
, th [] [ text "URL" ]
, th [] [ text "description" ]
]
]
, tbody [] (List.map facilityRow facilities)
]
]
facilityRow : Facility -> Html Msg
facilityRow facility =
let
openingTime = facility.opening
in
tr []
[ td [] [ text facility.id ]
, td [] [ editLink facility ]
, td [] [ text (openingTime.open ++ " - " ++ openingTime.close) ]
, td [] [ text facility.address ]
, td [] [ text facility.postcode ]
, td [] [ text facility.web_site ]
, td [] [ text facility.description ]
]
editLink : Facility -> Html Msg
editLink facility =
let
editPath = facilityPath facility.id
in
a [ href editPath ]
[ text facility.name ]
ブラウザで確認すると、以下のように施設名がリンクになり、どれかをクリックすると、パスが変わるのが確認できます。下の図は、「東京スカイツリー」をクリックした時のパスです。URLの最後に/#facilities/2
がくっついています。
これで、リンククリック -> パス書き換え まではできました。次は遷移先のページの作成と遷移時のルーティングを定義します。
elmでwebアプリ作成9 〜 施設個別ページとルーティング