4

Perl Template Toolkit - how to join / concat multiple variables (into one) for example wanting it when selecting the chosen element in a html select field/combo.

I found the question here https://www.perlmonks.org/?displaytype=print;replies=1;node_id=880584 , but it did not seem to be properly replied.

Dots, spaces or plus signs didn't help to join variables.

Edit: previously I managed to work it around just by using interpolation inside a string

[% var = "$var1-$var2-$var3" %]
FantomX1
  • 1,577
  • 2
  • 15
  • 23

1 Answers1

6

String concatenation is done with the underscore _. See the manual here. It's a bit hidden.

[%
   SET $foo = $bar _ $asdf _ " " _ $xyz
%]

For your example, that would be done like this, but interpolation works just as well.

[% var = $var1 _ "-" _ $var2 _ "-" _ $var3 %]
Polar Bear
  • 6,762
  • 1
  • 5
  • 12
simbabque
  • 53,749
  • 8
  • 73
  • 136
  • Thanks for your solution, however this does not seem to work inside this special case an array definition in template toolkit like this ` [% form = [ [ 'Date:' , todayDate _ macroSelectBox(data) ] %] ` . Any clues with this? – FantomX1 Mar 25 '21 at 10:26
  • I worked this around ` [% form = [ [ 'Date:' , todayDate _ macroSelectBox(data) ] %] ` by using another inner nested array and joining it later like this, but its a bit crude , ` [% form = [ [ 'Date:' , [ todayDate , macroSelectBox(data) ] ] %] ` – FantomX1 Mar 25 '21 at 11:23
  • 1
    @FantomX1 that is odd. You could make the second element in its own var first and put it in the array later? – simbabque Mar 25 '21 at 14:09
  • @simbaque thanks, thats also an option I was considering, but its not very transparent for example my array is 10 rows long, doing it like this its going to make it about twice that size = 20 additional rows for setting variables, just because of this – FantomX1 Mar 25 '21 at 16:58
  • 1
    @FantomX1 can you not do that in the backend rather than in the template? Or create anotehr `macroSelectBoxDate(data, todayDate)`? – simbabque Mar 25 '21 at 18:24
  • 1
    @simbaque yeah good thoughts, I could make it in the backend, but I feel like that approach is not very practical , effective and good practice. Another macro could work, but its still much more hassle I guess, than just joining them. The conclusion its syntax of template toolkit joining can't be said that works in any context of the template toolkit usages, since I did not exit template toolkit domain language , I presume, when I used it inside an array definition, I did not applied the perl tag, moreover, if it was raw perl, at least other options would work – FantomX1 Mar 25 '21 at 20:37