英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论