如何在程序启动时在elm中设置页面标题?
我在文档中找到了这个:(http://elm-lang.org/docs/syntax)
Elm有一些内置的端口处理程序,可以自动采取一些必要的操作:
title设置页面标题,忽略空字符串
但是我仍然无法完全绕过端口,也无法找到正在使用的特定端口的任何示例.所以我不知道,例如,甚至端口的类型签名.
我知道我可以通过制作我自己的index.html并将elm程序嵌入其中来做到这一点,但我想在榆树本身中解决这个问题,即使没有其他原因也要了解它是如何完成的.(并希望了解有关端口的信息......)
小智 17
从Elm v0.17开始,内置title端口已被删除,但是自己添加端口非常容易.以下程序将在启动时将页面标题设置为"This is the 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"
Run Code Online (Sandbox Code Playgroud)
然后,在Javascript中,您需要订阅端口:
var app = Elm.Main.fullscreen();
app.ports.title.subscribe(function(title) {
document.title = title;
});
Run Code Online (Sandbox Code Playgroud)
类型签名是您定义的任何类型.作为使用title端口设置标题的简单应用程序的示例:
import Html exposing (text)
port title : String
port title = "The page title"
main =
text "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
作为一个稍微复杂的示例,您可以将页面标题设置为每秒更新为当前时间
import Html exposing (text)
import Time exposing (every, second)
port title : Signal Float
port title = every second
main =
text "Hello, World!"
Run Code Online (Sandbox Code Playgroud)
在 Elm 0.19 中,定义了类型Browser.Document。
type alias Document msg =
{ title : String
, body : List (Html msg)
}
Run Code Online (Sandbox Code Playgroud)
该数据指定 和所有应该进入 的节点。这意味着您可以在应用程序发生变化时更新标题。也许您的“单页应用程序”导航到“不同的页面”,也许日历应用程序在标题中显示准确的日期,等等。
Browser.document如果您使用或创建程序Browser.application,则只需设置网页的标题即可。
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
}
Run Code Online (Sandbox Code Playgroud)