9

How can one use the equivalent of the implode function in a Twig environment?

For example, the contents of the variable $data1 = "input your name" and the variable $data2 = "input your address".

How to create a variable $result = "input your name, input your address" in Twig?

user1798945
  • 145
  • 1
  • 2
  • 7
  • 1
    I'm not sure I really get your question. I'm assuming you're talking about the Twig Template Engine for PHP, and want to assign the concatenated strings to a new variable? In that case it would be something like `{% set result = data1 ~ ", " ~ data2 %}`. But then I don't really get why you posted your question with '$'s in front of the variable names... If just want to output the two string, you could always do something like `{{data1}}, {{data2}}` – Andreas Wallner Nov 07 '12 at 10:08

1 Answers1

37

I'm guessing you're looking for the join filter. It works exactly like implode does in php. Quoting from the manual page:

The join filter returns a string which is the concatenation of the items of a sequence:

{{ [1, 2, 3]|join }}
{# returns 123 #}

The separator between elements is an empty string per default, but you can define it with the optional first parameter:

{{ [1, 2, 3]|join('|') }}
{# returns 1|2|3 #}
Maerlyn
  • 33,687
  • 18
  • 94
  • 85