How to Detect the Last Item in a Go Template Range?
Nov 08, 2024 am 06:24 AMDetecting the Last Item in a Template Range
In Go templates, iterating over arrays or slices using the range action allows for convenient access to array elements. However, sometimes it becomes necessary to distinguish the last iteration from the others.
Consider a template that requires distinct formatting for the last element in a range:
{{range $i, $e := .SomeField}} {{if $i}}, {{end}} $e.TheString {{end}}
This template would generate output like:
one, two, three
To modify this behavior and output "and" before the last element:
one, two, and three
one needs to determine which element in the range is the last.
Although it's possible to track the length of the array outside the template, this method would result in a static value that does not account for changes in the array's length.
The solution lies in leveraging Go's function injection capabilities for templates. By defining a custom function, it becomes feasible to dynamically identify the last element:
package main import ( "os" "reflect" "text/template" ) var fns = template.FuncMap{ "last": func(x int, a interface{}) bool { return x == reflect.ValueOf(a).Len() - 1 }, } func main() { t := template.Must(template.New("abc").Funcs(fns).Parse(`{{range $i, $e := .}}{{if $i}}, {{end}}{{if last $i $}}and {{end}}{{$e}}{{end}}.`)) a := []string{"one", "two", "three"} t.Execute(os.Stdout, a) }
This approach utilizes reflection to dynamically determine the length of the array and compare it to the current index $i. When the index matches the array length minus one, the last function returns true, indicating that the current element is the last in the range.
As an alternative, one can also use the len function without reflection:
package main import ( "os" "text/template" ) func main() { t := template.Must(template.New("abc").Parse(`{{range $i, $e := .}}{{if $i}}, {{end}}{{if len .}}and {{end}}{{$e}}{{end}}.`)) a := []string{"one", "two", "three"} t.Execute(os.Stdout, a) }
The above is the detailed content of How to Detect the Last Item in a Go Template Range?. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language pack import: What is the difference between underscore and without underscore?

How to implement short-term information transfer between pages in the Beego framework?

How to convert MySQL query result List into a custom structure slice in Go language?

How do I write mock objects and stubs for testing in Go?

How can I define custom type constraints for generics in Go?

How can I use tracing tools to understand the execution flow of my Go applications?

How to write files in Go language conveniently?
