How to Concatenate Strings and Variables in Twig?

Learn how to combine strings and variables in the twig templating engine for PHP

In this article, we will look at different ways to concatenate strings in a twig template. For the examples in this article, let's consider the following variables:

{% set foo = 'hello' %}
{% set bar = 'world' %}

Using String Interpolation

String interpolation allows any valid expression inside a double-quoted string. The expressions are evaluated and inserted into the string. Consider for example:

{{ "#{foo} #{bar}!" }}
// output: hello world!

{{ "#{foo} #{bar}!" | title }}
// output: Hello World!

{{ "1 + 1 = #{1 + 1}" }}
// output: 1 + 1 = 2

Using the ~ (Tilde) Operator

The tilde character concatenates all operands (strings and/or variables) into a single string. For example:

{{ foo ~ ' ' ~ bar ~ '!' }}
// output: hello world!

{{ foo|upper ~ ' ' ~ bar ~ '!' }}
// output: HELLO world!

{{ (foo ~ ' ' ~ bar ~ '!') | title }}
// output: Hello World!

{{ '1 + 1 = ' ~ (1 + 1) }}
// output: 1 + 1 = 2

As you can see from the examples above, it can be useful when there's a need to apply selective filters to a particular operand or to everything within a group (specified by parenthesis).

Using the format Filter

The format filter in twig is the same as PHP's sprintf notation. It formats a string by replacing the placeholders specified within it. For example:

{{ "%s %s!" | format(foo, bar) }}
// output: hello world!

{{ "%s %s!" | format(foo, bar) | title }}
// output: Hello World!

{{ "1 + 1 = %d" | format(1 + 1) }}
// output: 1 + 1 = 2

Joining an Array of Strings With join

An array of strings can be joined together into a single string like so:

{{ [foo, ' ', bar, '!'] | join }}
// output: hello world!

{{ [foo|upper, ' ', bar, '!'] | join }}
// output: HELLO world!

{{ [foo, ' ', bar, '!'] | join | title }}
// output: Hello World!

{{ ['1 + 1 = ', 1 + 1] | join }}
// output: 1 + 1 = 2

Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.