How to print comma-separated list with hamlet?

血红的双手。 提交于 2020-01-03 12:35:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!