如何用hamlet打印以逗号分隔的列表?

Joa*_*ner 6 templates haskell yesod hamlet

使用yesod附带的hamlet模板语言,打印逗号分隔列表的最佳方法是什么?

假设这个代码只打印一个接一个的条目,如何在元素之间插入逗号?或者甚至可能在最后一个条目之前添加"和":

The values in the list are
$ forall entry <- list
    #{entry}
and that is it.
Run Code Online (Sandbox Code Playgroud)

一些模板语言(如Template Toolkit)提供了检测第一次或最后一次迭代的指令.

ham*_*mar 5

我不认为有任何内置的东西.幸运的是,在哈姆雷特中使用辅助函数很容易.例如,如果您的项目是纯字符串,则可以使用Data.List.intercalate它们之间添加逗号.

The values in the list are 
#{intercalate ", " list} 
and that is it.
Run Code Online (Sandbox Code Playgroud)

如果你想做更好的事情,你可以编写函数来处理哈姆雷特值.例如,这是一个在列表中的哈姆雷特值之间添加逗号和"和"的函数.

commaify [x] = x
commaify [x, y] = [hamlet|^{x} and ^{y}|]
commaify (x:xs) = [hamlet|^{x}, ^{commaify xs}|]
Run Code Online (Sandbox Code Playgroud)

这使用^{...}语法将一个Hamlet值插入另一个.现在,我们可以使用它来编写以逗号分隔的带下划线的单词列表.

The values in the list are 
^{commaify (map underline list)} 
and that is it.
Run Code Online (Sandbox Code Playgroud)

在这里,underline只是一个小帮助函数,可以产生比纯文本更有趣的东西.

underline word = [hamlet|<u>#{word}|]
Run Code Online (Sandbox Code Playgroud)

渲染时,会得到以下结果.

The values in the list are <u>foo</u>, <u>bar</u> and <u>baz</u> and that is it.
Run Code Online (Sandbox Code Playgroud)