Responsive YouTube Videos With Elm

I recently wrote an navigation app for a hack day, and since it's written in Elm, and there aren't enough blog posts about Elm, I thought I'd break down some of the pieces. Let's warm up with a simple, but exceptionally useful one: Embedding a responsive video.

This is so easy it's almost cheating. Most of the hard work is offloaded to Bootstrap 3. But since it's so useful it's worth spelling out. All we need is a function that takes a YouTube URL, and returns some HTML. That translates to this type signature:

youtube : String -> Html

Then we need to know how to generate HTML in Elm. It's pretty easy. Almost every HTML function takes a list of attributes, followed by a list of children. So a Bootstrap alert messsage might be:

alert =
    div [ class "alert alert-danger" ]
        [ text "Ohnoes!" ]

...or with a title:

alert =
    div [ class "alert alert-danger" ]
        [ h1 []
            [ text "Error!" ]
        , text "Ohnoes!"

(You can see there in the h1 tag that you must specify the list of attributes, even if it's empty.)

With that, the code for our youtube function is an easy translation of the Bootstrap docs:

youtube url =
    div [ class "embed-responsive embed-responsive-16by9" ]
        [ iframe
            [ class "embed-responsive-item"
            , src url

And that's all there is to it.

(For the curious, I've published a slightly fancier version as a library.)