Text.Blaze中的可选html属性

Vag*_*rdi 3 html haskell

Text.Blaze有一个运营商!添加属性到html:

option ! id "bla" ! value "1" ! selected "" $ "Hello!"
Run Code Online (Sandbox Code Playgroud)

我的问题是如何使属性可选?现在我的代码很难看:

option ! id "bla" ! value "1" ! (if x == val then selected "" else someStupidAttribute "")  $ "Hello!"
Run Code Online (Sandbox Code Playgroud)

这导致每个html选项元素都有不必要的无关属性,因为我必须提供一个.

编辑:我接受了hammar的回答.我创建了一个辅助函数:

(!?) :: Attributable h => h -> (Bool,Attribute) -> h
html !? (True, attr) = html ! attr
html !? _ = html
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它:

option ! id "bla" ! value "1" !? ((k == val), selected "") $ "Hello!"
Run Code Online (Sandbox Code Playgroud)

ham*_*mar 5

如何定义一个方便运算符来有条件地应用属性?

(!?) :: Attributable h => h -> Maybe Attribute -> h
html !? (Just attr) = html ! attr
html !? Nothing = html
Run Code Online (Sandbox Code Playgroud)

有了这个,您可以按如下方式编写示例.

option ! id "bla" ! value "1" !? toMaybe (x == val) (selected "") $ "Hello!"
Run Code Online (Sandbox Code Playgroud)

在这里,toMaybe它只是构建Maybe值的有用助手,但如果您愿意,可以使用其他东西.

toMaybe :: Bool -> a -> Maybe a
toMaybe False _ = Nothing
toMaybe True  x = Just x
Run Code Online (Sandbox Code Playgroud)