How to concatenate strings in twig
Solution 1
This should work fine:
{{ 'http://' ~ app.request.host }}
To add a filter - like 'trans' - in the same tag use
{{ ('http://' ~ app.request.host) | trans }}
As Adam Elsodaney points out, you can also use string interpolation, this does require double quoted strings:
{{ "http://#{app.request.host}" }}
Solution 2
Also a little known feature in Twig is string interpolation:
{{ "http://#{app.request.host}" }}
Solution 3
The operator you are looking for is Tilde (~), like Alessandro said, and here it is in the documentation:
~: Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is 'John') Hello John!. – http://twig.sensiolabs.org/doc/templates.html#other-operators
And here is an example somewhere else in the docs:
{% set greeting = 'Hello' %}
{% set name = 'Fabien' %}
{{ greeting ~ name|lower }} {# Hello fabien #}
{# use parenthesis to change precedence #}
{{ (greeting ~ name)|lower }} {# hello fabien #}
Solution 4
In this case, where you want to output plain text and a variable, you could do it like this:
http://{{ app.request.host }}
If you want to concatenate some variables, alessandro1997's solution would be much better.
Solution 5
{{ ['foo', 'bar'|capitalize]|join }}
As you can see this works with filters and functions without needing to use set
on a seperate line.
stoefln
I'm a passionate programmer and designer, currently especially interested in Electron, JS, Android and Arduino.
Updated on July 27, 2022Comments
-
stoefln almost 2 years
Anyone knows how to concatenate strings in twig? I want to do something like:
{{ concat('http://', app.request.host) }}