如何在 golang 模板中获取切片的最后一个元素
我可以在这样的模板中获取切片的大小
I can get the size of a slice in a template like this
{{$size := len .Things}}
我可以像这样在模板中索引一个切片:
And I can index a slice in a template like this:
{{index .Things 4}}
但是
{{index .Things $size}}
给出超出范围"错误,因为索引切片是从零开始的.
gives an "out of range" error because indexing a slice is zero-based.
我是否已经完成了所有函数定义的事情,或者是否有我可以使用的算术?
Do I have do all the function defining things or is there arithmetic available I can use?
即我该怎么做 https://stackoverflow.com/a/22535888 但在 golang 模板中.
I.e. how do I do this https://stackoverflow.com/a/22535888 but in a golang template.
与其他语言或某些框架相比,Go 中的模板可能被视为更被动".被动视图的想法是它们不包含太多逻辑,而是将所有数据传递进来.
In go templates could be viewed as more "passive" than in other languages or some frameworks. The idea of passive views is that they do not include much logic but get passed all their data in.
因此您可以将LastThing"传递给您的模板,该模板分配了最后一件事.
So you could pass "LastThing" to your template, which has the last Thing assigned.
这不能直接回答您的问题,但这只是您可以考虑的替代方案.
This does not answer your question directly but this is just an alternative you could consider.