2013-07-15 63 views
5

我有一個使用http/template包的模板。如何迭代模板中的鍵和值?如何迭代Go html模板中的鍵和值映射

示例代碼:

template := ` 
<html> 
    <body> 
    <h1>Test Match</h1> 
     <ul> 
     {{range .}} 
      <li> {{.}} </li> 
     {{end}} 
    </ul> 
</body> 
</html>` 

dataMap["SOMETHING"] = 124 
dataMap["Something else"] = 125 
t, _ := template.Parse(template) 
t.Execute(w,dataMap) 

如何訪問鑰匙{{range}}模板

回答

7

有一兩件事你可以嘗試使用range分配兩個變量 - 一個用於密鑰,一個用於值。根據this更改(和docs),密鑰將按照可能的排序順序返回。下面是使用你的數據爲例:

package main 

import (
     "html/template" 
     "os" 
) 

func main() { 
     // Here we basically 'unpack' the map into a key and a value 
     tem := ` 
<html> 
    <body> 
    <h1>Test Match</h1> 
     <ul> 
     {{range $k, $v := . }} 
      <li> {{$k}} : {{$v}} </li> 
     {{end}} 
    </ul> 
</body> 
</html>` 

     // Create the map and add some data 
     dataMap := make(map[string]int) 
     dataMap["something"] = 124 
     dataMap["Something else"] = 125 

     // Create the new template, parse and add the map 
     t := template.New("My Template") 
     t, _ = t.Parse(tem) 
     t.Execute(os.Stdout, dataMap) 
} 

有把它處理可能更好的方法,但這在我的(很簡單)曾用例:)