19

For example, there is a function like that:

 func TestFunc(str string) string {
 return strings.Trim(str," ")
 }

It runs in the example below:

 {{ $var := printf "%s%s" "x" "y" }}
 {{ TestFunc $var }}

Is there anyway to concatenate strings with operators in template ?

 {{ $var := "y" }}
 {{ TestFunc "x" + $var }}

or

 {{ $var := "y" }}
 {{ TestFunc "x" + {$var} }}

It gives unexpected "+" in operand error.

I couldnt find it in documentation (https://golang.org/pkg/text/template/)

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Özgür Yalçın
  • 1,872
  • 3
  • 16
  • 26

1 Answers1

24

There is not a way to concatenate strings with an operator because Go templates do not have operators.

Use the printf function as shown in the question or combine the calls in a single template expression:

{{ TestFunc (printf "%s%s" "x" "y") }}

If you always need to concatenate strings for the TestFunc argument, then write TestFunc to handle the concatenation:

func TestFunc(strs ...string) string {
   return strings.Trim(strings.Join(strs, ""), " ")
}

{{ TestFunc "x"  $var }}
Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
  • 1
    see also @gyoza https://github.com/hashicorp/consul-template/issues/267#issuecomment-386416693 – 030 Mar 23 '20 at 20:31