dousunle5801 2017-03-08 03:37
浏览 120
已采纳

去模板删除范围循环中的最后一个逗号

I have code like this:

package main

import (
    "text/template"
    "os"
)

func main() {
    type Map map[string]string
    m := Map {
        "a": "b",
        "c": "d",
    }
    const temp = `{{range $key, $value := $}}key:{{$key}} value:{{$value}},{{end}}`
    t := template.Must(template.New("example").Parse(temp))
    t.Execute(os.Stdout, m)
}

it will output :

key:a value:b,key:c value:d,

but I want something like this:

key:a value:b,key:c value:d

I don't need the last comma, how to remove it. I found a solution for looping an array here: https://groups.google.com/d/msg/golang-nuts/XBScetK-guk/Bh7ZFz6R3wQJ , but I can't get index for a map.

  • 写回答

2条回答 默认 最新

  • doulanyan6455 2017-03-08 05:51
    关注

    Here's how to write comma separated key-value pairs using a template function.

    Declare a function that returns a function that increments and returns a counter:

    func counter() func() int {
        i := -1
        return func() int {
            i++
            return i
        }
    }
    

    Add this function to the template:

    t := template.Must(template.New("example").Funcs(template.FuncMap{"counter": counter}).Parse(temp))
    

    Use it in the template like this:

        {{$c := counter}}{{range $key, $value := $}}{{if call $c}}, {{end}}key:{{$key}} value:{{$value}}{{end}}
    

    This template writes the separators before the key-value pairs instead after the pairs.

    The counter is created before the loop and incremented on each iteration through the loop. The separator is not written the first time through the loop.

    Run it in the playground.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里