elm - 在elm中设置页面标题?

标签 elm

如何在程序启动时在 elm 中设置页面标题?
我在文档中找到了这个:( http://elm-lang.org/docs/syntax )

Elm has some built-in port handlers that automatically take some imperative action:

title sets the page title, ignoring empty strings


但是,我仍然无法完全了解端口,也找不到任何使用此特定端口的示例。所以我不知道,例如,甚至端口的类型签名。
我知道我可以通过制作我自己的 index.html 并将 elm 程序嵌入其中来做到这一点,但我想在 elm 本身中解决这个问题,即使除了了解它是如何完成的没有其他原因。 (希望也能学到一些关于端口的东西......)

最佳答案

从 Elm v0.17 开始,内置 title端口已被删除,但自己添加端口非常容易。以下程序将在启动时将页面标题设置为“这是标题”:

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"

然后,在 Javascript 中,您需要订阅端口:

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

关于elm - 在elm中设置页面标题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33612524/

相关文章:

url-redirection - Elm lang 重定向到外部 URL

elm - 在 elm 中赋值

elm - 有没有办法将两个参数通过管道传递给 Elm 中的函数?

json - 用 Elm 中的对象解码 Json 数组

f# - 使用 Fable-Elmish 上传文件

design-patterns - elm 中的翻译模式是什么?

elm - 对 "Html msg"感到困惑

html - 在没有 no-op 消息的情况下禁用 Elm 表单提交

elm - 通过端口将多个参数传递给Javascript

elm - Elm 0.18 中的本地范围更新