* Pawan Kumar <pawan....@gmail.com> [210528 12:43]: > Hi Team, > > I was using slice function to extract last 2 characters in go template but > not able to do ,as -ve range is not supported by slice function . > > For example - My cluster name is turbo-ab-03 , i can extract if i know > exact length of cluster name. > > {{ slice (index .ServiceMeta "cluster_name") 9 11}} > Results - 03 > > But it fails , if i use negative range ( Want to extract last 2 characters) > > {{ slice (index .ServiceMeta "cluster_name") -1 2}} > > kindly help. > > thanks
Neither the slice expression in the Go language, nor the slice function in the text/template and html/template packages allow negative slice indexes. Also, the template language does not allow arbitrary arithmetic expressions directly. However, you can define your own functions for the template and use them. In this playground example, «https://play.golang.org/p/yvFRYVe2Bu5», I defined a function "sub" that I use to calculate the correct arguments to the slice function. You can also use variables to avoid repeating long expressions: {{$c := index .ServiceMeta "cluster_name"}} {{slice $c (sub (len $c) 2) (len $c)}} ...Marvin -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/20210528185109.7hsu7m6kn5a5koar%40basil.wdw.