separate output list elements by delimiter in hamlet

84 views Asked by At

If I have the code below, how do I get rid of the last comma in the output? Is there a way to see where in the loop I am and whether I am at the end?

{-# 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},
                              |] ()

This produces ONE,2,3,, I need ONE,2,3. For any arbitrary list of course. Please help.

2

There are 2 answers

0
Sibi On BEST ANSWER

You can use intersperse function:

{-# 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}
                              |] ()

That will produce this:

ONE,2,3

Note that intersperse will insert intermediate , between your list. So, in the hamlet quasiquoter, you just display the list:

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

I think you have to implement this kind of logic on the Haskell side, e.g.:

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}] ...

Some visual effects which treat the first or last element of a sequence in a special way may also be implemented using CSS, i.e. using a <ul> and <li> tags.