我怎样才能在 Yesod 的另一个 Widget 中同时嵌入 Text 和 Widget?

How can I embed both Text and Widget in another Widget in Yesod?

给出一个像这样的简单例子

glyphicon :: Text -> Widget
glyphicon name = toWidget [hamlet|<span class="glyphicon glyphicon-#{name}">|]

foo :: ToMarkup a => a -> Widget
foo content = toWidget [hamlet|<div class="foo">#{content}</div>|]

Yesod 中是否有内置机制允许我同时执行 foo "some text"foo (glyphicon "pencil")?我已经设法通过使用将 Text 和 Widget 转换为 Widget

的自定义类型类来解决这个问题
class MakeWidget a where
  makeWidget :: a -> Widget

instance MakeWidget Widget where
  makeWidget = id

instance MakeWidget Text where
  makeWidget x = toWidget [hamlet|#{x}|]

glyphicon :: Text -> Widget
glyphicon name = toWidget [hamlet|<span class="glyphicon glyphicon-#{name}">|]

foo :: MakeWidget a => a -> Widget
foo content = toWidget [whamlet|<div class="foo">^{makeWidget content}</div>|]

但这感觉不对,尤其是由于类型不明确,我什至不能做 ^{foo "hello"},而不得不做 ^{foo (T.pack "hello")}

是否有更好的方法将 TextWidget 嵌入另一个 Widget

我不会走这条路,特别是因为您已经发现了类型推断问题。明确地不得不偶尔调用 toWidget 可能是这里最好的折衷方案。