I'm trying to fill in a table with the following template:
<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>
When I execute this template, it outputs:
<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>
When I run the template without the {{index}} call:
<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>
it outputs the complete range:
<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>
What could be causing the output to be interrupted in the first instance of my template?
When you execute a template an error is returned:
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())
The error is:
template: ex:9:20: executing "ex" at <.GitHubRepoNames>: can't evaluate field GitHubRepoNames in type string
Which means the .
is being changed to $e
. I'm not sure why you need to do the index like this ($e
seems like it ought to be sufficient) but you can do this:
<td>{{index $.GitHubRepoNames $i}}</td>
$
is explained by the documentation:
When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.