2014-09-05 9 views
10

मैं गो टेम्पलेट में एक बहुत ही सरल चीज़ प्राप्त करने और असफल होने की कोशिश कर रहा हूं! ,गो टेम्पलेट्स में अंकगणित

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

हालांकि मैं उत्पादन सूचकांक कि से 1. मेरे पहले ही प्रयास में विफल रहा है गिनती शुरू करने के लिए कोशिश कर रहा हूँ:

range कार्रवाई मुझे अपने शून्य आधारित सूचकांक के साथ एक सरणी के माध्यम से पुनरावृति करने के लिए, के रूप में इसलिए की अनुमति देता है :

Number: {{$index + 1}} 

यह एक illegal number syntax: "+" त्रुटि फेंकता है।

मैंने गो-लांग आधिकारिक दस्तावेज में देखा और टेम्पलेट के अंदर अंकगणितीय ऑपरेशन के बारे में कुछ विशेष नहीं मिला।

मुझे क्या याद आ रही है?

उत्तर

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

5

आप consul-template में इस्तेमाल के लिए एक जाओ टेम्पलेट लेखन कर रहे हैं तो, आप उनके संपर्क में arithmetic functions उपयोगी हो सकते हैं:

Number: {{add $index 1}}