在 hamlet 中用定界符分隔输出列表元素

separate output list elements by delimiter in hamlet

如果我有下面的代码,如何去掉输出中的最后一个逗号?有没有办法查看我在循环中的位置以及我是否在最后?

{-# LANGUAGE QuasiQuotes #-}

import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Hamlet (hamlet)

main = do
  let xs = [1 :: Int, 2, 3]
  putStrLn $ renderHtml $ [hamlet|
                              $forall x <- xs
                                $if x == 1
                                  ONE,
                                $else
                                  #{x},
                              |] ()

这产生ONE,2,3,,我需要ONE,2,3。当然对于任何任意列表。请帮忙。

我认为你必须在 Haskell 端实现这种逻辑,例如:

import Data.List (intercalate)

main = do
  let xs = [1 :: Int, 2, 3 ]
      str = intercalate "," $ map fmt xs
      fmt 1 = "ONE"
      fmt x = show x

  ... [hamlet| #{str}] ...

一些以特殊方式处理序列的第一个或最后一个元素的视觉效果也可以使用 CSS 实现,即使用 <ul><li> 标签。

您可以使用intersperse函数:

{-# LANGUAGE QuasiQuotes #-}

import Text.Blaze.Html.Renderer.String (renderHtml)
import Text.Hamlet (hamlet)
import Data.List (intersperse)

main = do
  let xs = intersperse "," $ map show [1 :: Int, 2, 3]
  putStrLn $ renderHtml $ [hamlet|
                              $forall x <- xs
                                $if x == "1"
                                  ONE
                                $else
                                  #{x}
                              |] ()

这将产生这个:

ONE,2,3

请注意 intersperse 将在您的列表之间插入中间 ,。因此,在 hamlet quasiquoter 中,您只需显示列表:

λ> intersperse "," $ map show [1,2,3]
["1",",","2",",","3"]