如何在程序启动时在 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/