如何打印与哈姆​​雷特逗号分隔的列表? [英] How to print comma-separated list with hamlet?

查看:104
本文介绍了如何打印与哈姆​​雷特逗号分隔的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用yesod附带的hamlet模板语言,打印逗号分隔列表的最佳方式是什么? 假设这个代码只是打印一个接一个的条目,我如何在元素之间插入逗号?或者,甚至可以在最后一项之前添加and:

 列表中的值是
$ forall项< - list
#{entry}
就是这样。

一些模板语言,如 Template Toolkit 提供指令来检测第一次或最后一次迭代。 / div>

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

 列表中的值是
#{intercalate,list
,就是这样。

如果您想做更有趣的事情,您可以编写函数来处理哈姆雷特值。例如,下面是一个函数,它在列表中的Hamlet值之间加上逗号和and。

  commaify [x] = x 
commaify [x,y] = [hamlet | ^ {x} and ^ {y} |]
commaify(x:xs)= [hamlet | ^ {x},^ {commaify xs} |

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

 列表中的值是
^ {逗号(地图下划线清单)}
就是这样。

在这里, underline 只是一个小帮手函数来产生比纯文本更有趣的东西。

  underline word = [hamlet |< u>#{word} |] 

呈现时,会得出以下结果。

 列表中的值是< u> foo< / u>,< u> bar< / u>和< u> baz< / u>就是这样。 


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.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.

这篇关于如何打印与哈姆​​雷特逗号分隔的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆