duannaxin9975 2014-09-09 05:20
浏览 4
已采纳

如何在Go文本/模板用法中使用.Key

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条回答 默认 最新

  • doushan2811 2014-09-09 05:24
    关注

    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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊