问题
With the hamlet templating language that comes with yesod, what is the best way of printing a comma-separated list?
E.g. assume this code which just prints one entry after another, how do I insert commas in between the elements? Or maybe even add an “and” before the last entry:
The values in the list are
$ forall entry <- list
#{entry}
and that is it.
Some templating languages such as Template Toolkit provide directives to detect the first or last iteration.
回答1:
I don't think there's anything built-in like that. Fortunately, it's easy to use helper functions in Hamlet. For example, if your items are plain strings, you can just use Data.List.intercalate
to add commas between them.
The values in the list are
#{intercalate ", " list}
and that is it.
If you want to do fancier things, you can write functions to work with Hamlet values. For example, here's a function which adds commas and "and" between the Hamlet values in a list.
commaify [x] = x
commaify [x, y] = [hamlet|^{x} and ^{y}|]
commaify (x:xs) = [hamlet|^{x}, ^{commaify xs}|]
This uses ^{...}
syntax to insert one Hamlet value into another. Now, we can use this to write a comma-separated list of underlined words.
The values in the list are
^{commaify (map underline list)}
and that is it.
Here, underline
is just a small helper function to produce something more interesting than plain text.
underline word = [hamlet|<u>#{word}|]
When rendered, this gives the following result.
The values in the list are <u>foo</u>, <u>bar</u> and <u>baz</u> and that is it.
来源:https://stackoverflow.com/questions/7534715/how-to-print-comma-separated-list-with-hamlet