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.
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.intercalateto add commas between them.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.
This uses
^{...}syntax to insert one Hamlet value into another. Now, we can use this to write a comma-separated list of underlined words.Here,
underlineis just a small helper function to produce something more interesting than plain text.When rendered, this gives the following result.