18

I'm writing a function that displays error messages, so in my view, I have something like

div [] [ displayErrors model ]

in the event that there are no errors, how can I make displayErrors return something that is interpreted as an empty Html node?

jz87
  • 9,199
  • 10
  • 37
  • 42

2 Answers2

29

You can use an Html.text node with an empty string:

emptyNode = Html.text ""
robertjlooby
  • 7,160
  • 2
  • 33
  • 45
  • 3
    Does this get optimized away? I'm concerned about using these phantom nodes because of the possibility of triggering some CSS rule that leads to unintended results. – jz87 Jul 27 '16 at 15:26
  • @jz87 looks like nothing gets rendered – rpearce Jan 08 '17 at 05:45
10

@robertjlooby's answer looks perfectly fine to me.

However, if you really want not to have any node, you could make displayErrors return a Maybe (Html msg).

Then, you can change your code to the following:

import Maybe.Extra exposing (maybeToList)

div [] ( displayErrors model |> maybeToList )

When displayErrors returns Nothing, the div will be really empty.

Note: you can install the Maybe.Extra module with the following command:

elm package install elm-community/maybe-extra
Zimm i48
  • 2,901
  • 17
  • 26
  • Yeah, this is a nice solution. The only problem is, if I'm using this in a list. So for example: div [] [ stuff, (displayErrors model |> maybeToList) ], this wouldn't really work. I guess there is no really good way to address this with the existing Html function signatures. Maybe the return signature should be Maybe (Html Msg) instead of Html Msg. – jz87 Jul 29 '16 at 21:13
  • 1
    In that case you can concatenate lists: `div [] ([stuff] ++ (displayErrors model |> maybeToList))` – Zimm i48 Jul 30 '16 at 09:31