英文:
GoLang hangs in template indexing
问题
我正在尝试使用以下模板填充表格:
<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>
当我在模板中去掉{{index}}调用时:
<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>
在模板的第一个实例中,可能是什么原因导致输出被中断?
英文:
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?
答案1
得分: 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())
错误信息为:
template: ex:9:20: 在类型为字符串的字段中无法评估字段GitHubRepoNames
这意味着.
被更改为$e
。我不确定为什么需要这样做索引($e
似乎足够了),但你可以这样做:
<td>{{index $.GitHubRepoNames $i}}</td>
$
在文档中有解释:
当执行开始时,$被设置为传递给Execute的数据参数,即dot的初始值。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论