【问题标题】:How can I embed both Text and Widget in another Widget in Yesod?如何在 Yesod 的另一个 Widget 中同时嵌入 Text 和 Widget?
【发布时间】:2015-02-14 13:41:24
【问题描述】:

举个简单的例子

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")}。

有没有更好的方法将Text 和Widget 嵌入到另一个Widget 中?

【问题讨论】:

    标签: haskell yesod hamlet


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-24
      • 1970-01-01
      • 2021-05-19
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 2021-12-19
      相关资源
      最近更新 更多