extract Last 2 characters in go template

322 views
Skip to first unread message

Pawan Kumar

unread,
May 28, 2021, 12:43:57 PM5/28/21
to golang-nuts
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 

Marvin Renich

unread,
May 28, 2021, 2:51:35 PM5/28/21
to golang-nuts
* Pawan Kumar <pawa...@gmail.com> [210528 12:43]:
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

Pawan Kumar

unread,
May 30, 2021, 8:03:48 AM5/30/21
to golang-nuts
Many thanks Marvin , really appreciate it.

Regards 

--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/20210528185109.7hsu7m6kn5a5koar%40basil.wdw.

Marvin Renich

unread,
May 30, 2021, 8:11:29 AM5/30/21
to golang-nuts
* Pawan Kumar <pawa...@gmail.com> [210530 08:03]:
> Many thanks Marvin , really appreciate it.

I intended, but forgot, to hint that your FuncMap could include a
function that was more specific to your problem than the sub function.

...Marvin

Reply all
Reply to author
Forward
0 new messages