2

I don't understand the document paragraph in http://golang.org/pkg/text/template/

- The name of a key of the data, which must be a map, preceded
  by a period, such as
    .Key
  The result is the map element value indexed by the key.
  Key invocations may be chained and combined with fields to any
  depth:
    .Field1.Key1.Field2.Key2
  Although the key must be an alphanumeric identifier, unlike with
  field names they do not need to start with an upper case letter.
  Keys can also be evaluated on variables, including chaining:
    $x.key1.key2

Here is my test code, but failed. code: http://play.golang.org/p/lbLJ4yoL2T.

var season = map[int]string{1: "spring", 2: "summer",              
        3: "autumn", 4: "winter"}                                  

func main() {                                                      
        const greeting = `Welcome, {{.Key}}`                       
        t := template.Must(template.New("greet").Parse(greeting))  
        err := t.Execute(os.Stdout, season)                        
        if err != nil {                                            
                fmt.Println(err)                                   
        }                                                          
}                                                                  

Output

Welcome, template: greet:1:11: executing "greet" at <.Key>: can't evaluate field Key in type map[int]string

1 Answer 1

1

I'd assume "Key" is the key (as in key/value) of the map. Also, the map keys can't be an int to use it in the template like that. So instead of {{.Key}} try {{.a}} as shown in this fork of your playground:

var season = map[string]string{"a": "spring", "b": "summer",              
        "c": "autumn", "d": "winter"}                                  

func main() {                                                      
        const greeting = `Welcome, {{.a}}`                       
        t := template.Must(template.New("greet").Parse(greeting))  
        err := t.Execute(os.Stdout, season)                        
        if err != nil {                                            
                fmt.Println(err)                                   
        }                                                          
}                                                                  

Output:

Welcome, spring
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.