Set the page title in elm?

In Elm 0.19, there is the type Browser.Document defined.

type alias Document msg =
    { title : String
    , body : List (Html msg)
    }

This data specifies the and all of the nodes that should go in the . This means you can update the title as your application changes. Maybe your "single-page app" navigates to a "different page", maybe a calendar app shows an accurate date in the title, etc.

If you create your program with Browser.document or Browser.application, you can simply set the title of your web page.

view : Model -> Browser.Document Msg
view model =
    { title = "This goes to the title"
    , body = [ text "Hello world!" ]
    }

main : Program Flags Model Msg
main =
    Browser.document
        { init = init
        , view = view
        , update = update
        , subscriptions = subscriptions
        }

As of Elm v0.17 the built-in title port has been removed, but it's very easy to add the port yourself. The following program will set the page title to "This is the title" at launch:

port module Main exposing (..)

import Html.App as App
import Html exposing (Html, text)

main =
  App.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }

port title : String -> Cmd a

type alias Model = {}

init : (Model, Cmd Msg)
init =
  ({}, title "This is the title")


type Msg
  = Noop

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
  case msg of
    Noop ->
      (model, Cmd.none)

subscriptions : Model -> Sub Msg
subscriptions model =
  Sub.none

view : Model -> Html Msg
view model =
  text "Hello World"

Then, in Javascript you need to subscribe to the port:

var app = Elm.Main.fullscreen();
app.ports.title.subscribe(function(title) {
    document.title = title;
});

The type signature is whatever you define it to be. As an example of a simple app using the title port to set the title:

import Html exposing (text)

port title : String
port title = "The page title"

main =
  text "Hello, World!"

As a slightly more complex example you could set the page title to update to the current time every second

import Html exposing (text)
import Time exposing (every, second)

port title : Signal Float
port title = every second

main =
    text "Hello, World!"

Tags:

Elm