Reputation: 29536
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.
Upvotes: 1
Views: 83
Reputation: 48654
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"]
Upvotes: 1
Reputation: 52039
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.
Upvotes: 2