如何在Beego的模板文件中获取范围的索引?

huangapple go评论70阅读模式
英文:

How to get the index of range in Beego's template file

问题

例如

{{ range .cars }} 
{{.color}} , ${{.price}} 
{{ end }}

'cars'数组的大小为10。我如何获取索引值?

当索引为5时,我想执行一些处理。

我正在使用Beego web框架。

英文:

For example

{{ range .cars }} 
{{.color}} , ${{.price}} 
{{ end }}

The array size of 'cars' is 10. How do I get the index value?

When the index is 5, I want do some process.

I am using Beego web framework.

答案1

得分: 0

首先,你的问题的答案已经在topskip的评论中给出。

range $index, $element := pipeline

请参阅golang.org/pkg/text/template/#hdr-Variables上的文档。

其次,要记住,当你开始在模板中添加逻辑,比如对第5个元素进行不同处理时,模板很快就会变得过于复杂。

考虑到这一点,最好尝试设计简单的视图模型,以便于渲染。在你的控制器中可能需要更多的逻辑,但在那里进行测试通常更容易。或者,考虑使用用Go编写的辅助工具。

模板中的逻辑越少,事情通常就越容易。

英文:

First of all, the answer to your question was given in the comment by topskip.

range $index, $element := pipeline

See the documentation at golang.org/pkg/text/template/#hdr-Variables.

Secondly, bear in mind that templates rapidly get too complex when you start putting logic in, such as treating the 5th element differently.

With this in mind, it is a good idea instead to try to design the view models so that they are simple to render. More logic might be needed in your controllers, but it's usually easier to test there. Alternatively, consider using helper utilities written in Go.

Less logic in the templates will make things generally easier.

huangapple
  • 本文由 发表于 2014年6月26日 19:22:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/24429215.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定