2014-09-05 324 views
10

我正试图在Go模板中实现一个非常简单的事情并失败!Go模板中的算术

range动作让我通过与它的索引(从零开始)沿迭代一个数组,像这样:

{{range $index, $element := .Pages}} 
    Number: {{$index}}, Text: {{element}} 
{{end}} 

不过,我想该开始从1我第一次尝试失败计数输出指数:

Number: {{$index + 1}} 

这会引发illegal number syntax: "+"错误。

我查看了go-lang官方文档,没有发现任何有关模板内部算术运算的特殊内容。

我错过了什么?

回答

13

您必须编写一个自定义函数来执行此操作。

http://play.golang.org/p/WsSakENaC3

package main 

import (
    "os" 
    "text/template" 
) 

func main() { 
    funcMap := template.FuncMap{ 
     // The name "inc" is what the function will be called in the template text. 
     "inc": func(i int) int { 
      return i + 1 
     }, 
    } 

    var strs []string 
    strs = append(strs, "test1") 
    strs = append(strs, "test2") 

    tmpl, err := template.New("test").Funcs(funcMap).Parse(`{{range $index, $element := .}} 
    Number: {{inc $index}}, Text:{{$element}} 
{{end}}`) 
    if err != nil { 
     panic(err) 
    } 
    err = tmpl.Execute(os.Stdout, strs) 
    if err != nil { 
     panic(err) 
    } 
} 
+1

嗨,你的答复非常感谢。这正是我需要的:) – Ripul 2014-09-08 11:42:48