How can I join strings in Go template without template functions?

huangapple go评论94阅读模式
英文:

How can I join strings in Go template without template functions?

问题

我有一个字符串切片,像 x := []string{a,b,c},最终我希望它变成 a+"/"+b+"/"+c

我正在尝试解决的问题来自于 Go 模板。
我希望在 Go 模板中找到一个解决方案。

以下是我目前的解决方案,但显然很丑陋。

res := {{range item := .x}}item+"/"{{end}}
res = res[:len(res)-1]

如果你有更好的方法,我会很感激!

英文:

I have a string slice, like x := []string{a,b,c}, and eventually I want it to be like a+"/"+b+"/"+c.

The problem I'm trying to deal with is coming from the Go template.
I want to have a solution in Go template.

The following is my current solution, but it's obviously ugly.

res := {{range item := .x}}item+"/"{{end}}
res = res[:len(res)-1]

If you have better approaches, appreciate it!

答案1

得分: 2

使用以下代码将切片与 / 连接起来:

{{range $i, $v := .x}}{{if $i}}/{{end}}{{$v}}{{end}}

在 playground 上运行示例

英文:

Use the following code to join a slice with /:

{{range $i, $v := .x}}{{if $i}}/{{end}}{{$v}}{{end}}

Run the example on the playground.

huangapple
  • 本文由 发表于 2021年9月12日 01:42:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/69145367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定