2013-12-21 49 views
2

我想填個表,下面的模板:GoLang掛在模板索引

<table class="table"> 
    <tr> 
     <td>Repo name</td> 
     <td>Repo id</td> 
    </tr> 
    {{range $i, $e := .GitHubRepoNames}} 
    <tr> 
     <td>{{$e}}</td> 
     <td>{{index .GitHubRepoNames $i}}</td> 
    </tr> 
    {{end}} 
</table> 

當我執行這個模板,它輸出:

<table class="table"> 
      <tr> 
       <td>Repo name</td> 
       <td>Repo id</td> 
      </tr> 

      <tr> 
       <td>https://api.github.com/repos/ertemplin/cah/issues{/number}</td> 
       <td> 

當我運行模板而不{{索引}}呼叫:

<table class="table"> 
    <tr> 
     <td>Repo name</td> 
     <td>Repo id</td> 
    </tr> 
    {{range $i, $e := .GitHubRepoNames}} 
    <tr> 
     <td>{{$e}}</td> 
     <td>{{$i}}</td> 
    </tr> 
    {{end}} 
</table> 

它輸出完整的範圍:

<table class="table"> 
      <tr> 
       <td>Repo name</td> 
       <td>Repo id</td> 
      </tr> 

      <tr> 
       <td>https://api.github.com/repos/ertemplin/cah/issues{/number}</td> 
       <td>0</td> 
      </tr> 
</table> 

什麼可能導致輸出在我的模板的第一個實例中被中斷?

回答

6

當你執行一個模板,將返回錯誤:

var buf bytes.Buffer 
err := tpl.Execute(&buf, map[string]interface{}{ 
    "GitHubRepoNames": []string{ 
     "https://api.github.com/repos/ertemplin/cah/issues{/number}", 
    }, 
}) 
fmt.Println(err, buf.String()) 

的錯誤是:

模板:前:9:20:在< .GitHubRepoNames執行 「前」>:可以評估字段類型中的字段GitHubRepoNames

這意味着.正在更改爲$e。我不知道爲什麼你需要做這樣的指數($e好像它應該是足夠了),但你可以這樣做:

<td>{{index $.GitHubRepoNames $i}}</td> 

$由文檔解釋當執行開始時,$被設置爲傳遞給Execute的數據參數,也就是點的起始值。

+0

我正在使用索引訪問另一個數組中的某些東西,而不是製作一個元組結構。感謝你的回答! – ertemplin