使用Elm的Html
模块,输出在html标记之间没有任何空格。但对于内联显示的标签,空格具有一个功能,并使浏览器在它们之间显示空白区域。
div []
[ strong [] [ text "Key:" ]
, span [] [ text "value" ]
, text "(extra)"
]
结果是:
<div><strong>Key:</strong><span>value</span>(extra)</div>
在浏览器中显示为:键:值(额外)
所需的html必须有某种空格:
<div>
<strong>Key:</strong>
<span>value</span>
(extra)
</div>
在浏览器中显示为:键:值(额外)
您可以为Html
标签创建一个包装器,如下所示:
type alias HtmlTag msg =
List (Html.Attribute msg) -> List (Html msg) -> Html msg
interspaced : HtmlTag msg -> HtmlTag msg
interspaced fn =
\attr content -> fn attr (content |> List.intersperse (text " "))
main : Html msg
main =
interspaced div []
[ strong [] [ text "Key:" ]
, span [] [ text "value" ]
, text "(extra)"
]
您可以手动在元素之间放置空格:
div []
[ strong [] [ text "Key:" ]
, text " "
, span [] [ text "value" ]
, text " "
, text "(extra)"
]
或者如果你想要更通用的东西,你可以使用List.intersperse
轻松编写一个函数,例如:
withSpacing : List (Html msg) -> List (Html msg)
withSpacing =
List.intersperse (text " ")
main : Html msg
main =
div []
(withSpacing
[ strong [] [ text "Key:" ]
, span [] [ text "value" ]
, text "(extra)"
]
)
或者更方便,基于合理的假设,你将它应用于一个函数,该函数将一个子元素列表生成一个元素:
withSpacing : (List (Html msg) -> Html msg) -> List (Html msg) -> Html msg
withSpacing element =
List.intersperse (text " ") >> element
main : Html msg
main =
withSpacing (div [])
[ strong [] [ text "Key:" ]
, span [] [ text "value" ]
, text "(extra)"
]