Golang在模板中用逗号分隔项目 [英] Golang separating items with comma in template

查看:39
本文介绍了Golang在模板中用逗号分隔项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试显示用逗号分隔的值的列表,并且不想在最后一项(如果只有一个,则为唯一项)之后显示逗号.

I am trying to display a list of comma separated values, and don't want to display a comma after the last item (or the only item if there is only one).

到目前为止,我的代码:

My code so far:

Equipment:
    {{$equipment := .Equipment}}
    {{ range $index, $element := .Equipment}}
        {{$element.Name}}
        {{if lt $index ((len $equipment) -1)}}
            ,
        {{end}}
    {{end}}

当前输出:设备:Mat,哑铃如何摆脱尾随逗号

The current output: Equipment: Mat , Dumbbell , How do I get rid of the trailing comma

推荐答案

您可以使用的一个不错的技巧是:

A nice trick you can use is:

Equipment:
    {{$equipment := .Equipment}}
    {{ range $index, $element := .Equipment}}
        {{if $index}},{{end}}
        {{$element.Name}}
    {{end}}

之所以有效,是因为第一个索引是 0 ,它在 if 语句中返回 false .因此,此代码为第一个索引返回 false ,然后在每个后续迭代的前面放置一个逗号.这样会导致逗号分隔的列表中没有前导逗号或尾随逗号.

This works because the first index is 0, which returns false in the if statement. So this code returns false for the first index, and then places a comma in front of each following iteration. This results in a comma separated list without a leading or trailing comma.

这篇关于Golang在模板中用逗号分隔项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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