<p>I must be missing something obvious here...</p>
<p>My data types are defined like this:</p>
<pre><code>struct {
FooCollections map[int64][]*Foo,
Users []*User
}
</code></pre>
<p>I have verified that Users and FooCollections contain all that I expected.</p>
<p>On my template, I want to loop over Users and access FooCollections by User.ID:</p>
<pre><code>{{ range $user := .Users }}
<!-- This works, as expected. -->
<div>{{ $user.ID }}</div>
<!--
This does not work, there's no error returned, just blanks.
And the <div> aren't rendered as well, which means range is not doing what it supposed to do.
-->
{{ range $foo := index .FooCollections $user.ID }}
<div>{{ $foo.Name }}</div> <!-- Name is just a string -->
{{ end }}
{{ end }}
</code></pre>
<p>Appreciate the help.</p>
<p><strong><a href="/u/polaris1119">/u/polaris1119</a> Answered</strong></p>
<pre><code>{{ range $foo := index $.FooCollections $user.ID }}
<div>{{ $foo.Name }}</div>
{{ end }}
</code></pre>
<p>Notice the '$' before '.FooCollections'</p>
<hr/>**评论:**<br/><br/>polaris1119: <pre><p>try {{ range $foo := index $.FooCollections $user.ID }} ?</p></pre>pinpinbo: <pre><p>OMG!!! That's it!</p>
<p>Could you kindly explains what '$' does? Or point me at the right docs?</p></pre>polaris1119: <pre><p>$ is always the root data. </p>
<p>{{ range $user := .Users }} had change "."</p></pre>om0tho: <pre><p><a href="http://golang.org/pkg/text/template/" rel="nofollow">http://golang.org/pkg/text/template/</a></p></pre>om0tho: <pre><p>Are you getting blanks because you're not printing anything?</p>
<pre><code>{{ range $foo := index .FooCollections $user.ID }}
{{$foo}}
{{ end }}
</code></pre>
<p>Also, have you implemented Stringer on Foo?</p></pre>pinpinbo: <pre><p>Ah, I should have been more clear, there are HTML contents inside the range. I've updated the question.</p>
<p>And no, I don't know about Stringer. What does it do? Do you have links/docs about it? </p></pre>om0tho: <pre><p><a href="https://golang.org/pkg/fmt/#Stringer" rel="nofollow">https://golang.org/pkg/fmt/#Stringer</a></p>
<p>The Stringer interface means that your object has a method called String on it. fmt.Print calls String automatically. I'm not sure, but <em>I think</em> templates do it too.</p>
<p>(That's a wild guess, I didn't try writing any code!)</p>
<p>Also, it looks like you found an answer! Hurray!</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传