Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print comma-separated list with hamlet?

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.

like image 581
Joachim Breitner Avatar asked Sep 23 '11 20:09

Joachim Breitner


People also ask

How do you write a comma-separated list?

When making a list, commas are the most common way to separate one list item from the next. The final two items in the list are usually separated by "and" or "or", which should be preceeded by a comma. Amongst editors this final comma in a list is known as the "Oxford Comma".

How do you print a comma-separated list in Python?

Without using loops: * symbol is use to print the list elements in a single line with space. To print all elements in new lines or separated by comma use sep=”\n” or sep=”, ” respectively.

What is a list of numbers separated by commas?

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record.


1 Answers

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.
like image 97
hammar Avatar answered Sep 27 '22 23:09

hammar