除了可以parse html,css之外,還有一個很常用的格式markdown,譬如這個鐵人賽的編輯器就是要你寫markdown,會幫你parse成html。elm也有這個一個套件elm-markdown裡面也很簡單,就只有一個function叫 toHtml
content : Html msg
content =
Markdown.toHtml [class "content"] """
# Apple Pie Recipe
1. Invent the universe.
2. Bake an apple pie.
"""
你也可以立刻用elm寫一個編輯器,讓你一邊輸入,一邊可以立刻得到html的結果:online-markdown-editor
-- 我有省略一些,這不是原來會動的code, 只是方便閱讀
module MarkdownEditor exposing (..)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Markdown
type alias Model =
{ input : String }
type Msg =
Input String
update : Msg -> Model -> (Model, Cmd Msg)
update msg {input} =
case msg of
Input newStr ->
(Model newStr, Cmd.none)
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
init : (Model, Cmd Msg)
init =
(Model defaultText, Cmd.none)
view : Model -> Html Msg
view model =
div [ class "view" ]
[ div [ class "jumbotron" ]
[ div [ class "container" ]
[ h1 [ class "display-3" ]
[ text "Elm Markdown Editor" ]
, p [ class "lead" ]
[ text "This is an online markdown editor written in Elm." ]
, hr [ class "my-4"]
[]
, p [ class "lead" ]
[ a [ class "btn btn-primary button-lg"
, href "https://github.com/3tty0n/elm-online-markdown-editor"
] [ text "Source"]
, a [ class "btn btn-secondary button-lg"
, href "https://github.com/3tty0n"
] [ text "Profile" ]
]
]
]
, div [ class "view" ]
[ div
[ class "row panes"
, panes
]
[ div [ class "col-xs-1" ]
[]
, div [ class "col-md-5 edit"
, textArea
, row
] [ textarea [ value model.input
, onInput Input
, class "inputarea"
, inputArea
, row
] []
]
, div [ class "col-md-5 display"
, display
, row
] [ Markdown.toHtml [] model.input ]
]
]
]
main : Program Never Model Msg
main =
program
{ init = init
, update = update
, view = view
, subscriptions = subscriptions
}
在 view
裡頭,放了一個 onInput
, 當你有新的輸入,就會呼叫 update
的 Input
Msg
,
讓你可以立刻看到你的markdown變成html。裡面就是使用這個 Markdown.toHtml