Template conditional

xuanbao · · 549 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I have a working template that shows the &#34;role&#34; a person plays in an organization but that same person may have more than one role. I would like to insert the word &#34;and&#34; between his two roles using an &#34;if&#34; conditional if that&#39;s the proper method.</p> <p>This is what I have:</p> <pre><code>Role: []string { &#34;Architect&#34;, &#34;Engineer&#34;, } {{range .Role}}&lt;span&gt;{{.}}&lt;/span&gt;{{end}} </code></pre> <p>I tried doing this:</p> <pre><code>{{range .Role}}&lt;span&gt;{{.}}&lt;/span&gt;{{if .}}and{{end}}{{end}} </code></pre> <p>but that adds &#34;and&#34; after both roles.</p> <p>How do I get it to put &#34;and&#34; only between each role when there&#39;s more than one?</p> <hr/>**评论:**<br/><br/>egonelbre: <pre><p><a href="https://play.golang.org/p/hDmc2rszJ-" rel="nofollow">https://play.golang.org/p/hDmc2rszJ-</a></p></pre>dhdfdh: <pre><p>Not quite but I see where you&#39;re going. You show </p> <pre><code>roles := []string{ &#34;Architect&#34;, &#34;Engineer&#34;, } </code></pre> <p>which may be why I get </p> <blockquote> <p>at &lt;.&gt;: range can&#39;t iterate over {[Architect Engineer] company-name 2014}</p> </blockquote> <p>Possibly because &#34;Role&#34; is part of an outer slice? </p> <pre><code>People: []AllPeople { Role: []string { &#34;Architect&#34;, &#34;Engineer&#34;, } } </code></pre></pre>IntellectualReserve: <pre><p>Try posting your revision on the playground?</p></pre>dhdfdh: <pre><p>I should really remember to do that when I ask these questions. Working on it now but getting a simplified version is ... difficult.</p></pre>mc_hammerd: <pre><p>yea i think that works, you just have to put another loop for &#39;.Role&#39;</p> <p>ala <a href="https://play.golang.org/p/YlQPrEjfp6" rel="nofollow">https://play.golang.org/p/YlQPrEjfp6</a></p></pre>dhdfdh: <pre><p>You&#39;re a lot closer. My code may need adjusting for your example. The output now is</p> <blockquote> <p>Architect Architect Engineer and Engineer</p> </blockquote> <p>EDIT: Whoops! It works. I just needed to remove one line of my code. Thanks!</p></pre>aarondl: <pre><p><a href="https://play.golang.org/p/ad_RpNApZq" rel="nofollow">https://play.golang.org/p/ad_RpNApZq</a></p> <p>Alternative way of doing the same.</p></pre>dhdfdh: <pre><p>Cool. Thanks.</p></pre>

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

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