2013-07-15 13 views
5

Ho un modello in uso utilizzando il pacchetto http/template. Come faccio a scorrere su entrambe le chiavi e i valori nel modello?Come eseguire iterazioni su chiavi e valori di una mappa in un modello Go html

codice Esempio:

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) 

Come posso accedere la chiave nella {{range}} nel modello

risposta

7

Una cosa che si potrebbe provare sta usando range per assegnare due variabili - una per la chiave, uno per il valore. Per modifica this (e docs), le chiavi vengono restituite in ordine, ove possibile. Ecco un esempio utilizzando i dati:

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) 
} 

Ci sono probabilmente migliori modi di gestire, ma questo ha lavorato nel mio (molto semplice) casi d'uso :)

Problemi correlati