dras2334 2012-05-25 00:30
浏览 183
已采纳

Google Go文本模板中范围的最后一个元素的特殊情况处理

I'm trying to write a string looking like this using go's template system: (p1, p2, p3), where p1, p2, ... comes from an array in the program. My problem is how to place the comma properly for the last (or the first) element.

My non working version that outputs (p1, p2, p3, ) looks like this:

package main

import "text/template"
import "os"
func main() { 
    ip := []string{"p1", "p2", "p3"}
    temp := template.New("myTemplate")
    temp,_ = temp.Parse(paramList)
    temp.Execute(os.Stdout, ip)

}

const paramList = 
`{{ $i := . }}({{ range $i }}{{ . }}, {{end}})`

My best clue so far is found here http://golang.org/pkg/text/template/ in the following statement:

If a "range" action initializes a variable, the variable is set to the successive elements of the iteration. Also, a "range" may declare two variables, separated by a comma:

$index, $element := pipeline

in which case $index and $element are set to the successive values of the array/slice index or map key and element, respectively. Note that if there is only one variable, it is assigned the element; this is opposite to the convention in Go range clauses. where it's suggested that the index

This suggests that it's possible to get hold of the index in the iteration but I just can't figure out what is meant with the range declaring two variables and where in the template those variables are supposed to be declared.

  • 写回答

1条回答 默认 最新

  • dongwujie7477 2012-05-25 03:02
    关注

    See this example from the go-nuts mailing list. One key to this trick is that a template if is different than a Go language if. A template can test for a value of zero, unlike the Go language that requires a boolean. The magic is then {{if $index}},{{end}} where $index needs no declaration other than its appearance in the assignment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch