How to access map of slice on html/template?

agolangf · · 1038 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<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 }} &lt;!-- This works, as expected. --&gt; &lt;div&gt;{{ $user.ID }}&lt;/div&gt; &lt;!-- This does not work, there&#39;s no error returned, just blanks. And the &lt;div&gt; aren&#39;t rendered as well, which means range is not doing what it supposed to do. --&gt; {{ range $foo := index .FooCollections $user.ID }} &lt;div&gt;{{ $foo.Name }}&lt;/div&gt; &lt;!-- Name is just a string --&gt; {{ 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 }} &lt;div&gt;{{ $foo.Name }}&lt;/div&gt; {{ end }} </code></pre> <p>Notice the &#39;$&#39; before &#39;.FooCollections&#39;</p> <hr/>**评论:**<br/><br/>polaris1119: <pre><p>try {{ range $foo := index $.FooCollections $user.ID }} ?</p></pre>pinpinbo: <pre><p>OMG!!! That&#39;s it!</p> <p>Could you kindly explains what &#39;$&#39; 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 &#34;.&#34;</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&#39;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&#39;ve updated the question.</p> <p>And no, I don&#39;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&#39;m not sure, but <em>I think</em> templates do it too.</p> <p>(That&#39;s a wild guess, I didn&#39;t try writing any code!)</p> <p>Also, it looks like you found an answer! Hurray!</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1038 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传