[syntax] How to concatenate strings in twig

Anyone knows how to concatenate strings in twig? I want to do something like:

{{ concat('http://', app.request.host) }}

This question is related to syntax twig string-concatenation templating

The answer is


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.


Whenever you need to use a filter with a concatenated string (or a basic math operation) you should wrap it with ()'s. Eg.:

{{ ('http://' ~ app.request.host) | url_encode }}


Also a little known feature in Twig is string interpolation:

{{ "http://#{app.request.host}" }}

Quick Answer (TL;DR)

  • Twig string concatenation may also be done with the format() filter

Detailed Answer

Context

  • Twig 2.x
  • String building and concatenation

Problem

  • Scenario: DeveloperGailSim wishes to do string concatenation in Twig
    • Other answers in this thread already address the concat operator
    • This answer focuses on the format filter which is more expressive

Solution

  • Alternative approach is to use the format filter
  • The format filter works like the sprintf function in other programming languages
  • The format filter may be less cumbersome than the ~ operator for more complex strings

Example00

  • example00 string concat bare

    
    {{ "%s%s%s!"|format('alpha','bravo','charlie') }}
    
    --- result --
    
    alphabravocharlie!
    
    

Example01

  • example01 string concat with intervening text

    
    {{ "The %s in %s falls mainly on the %s!"|format('alpha','bravo','charlie') }}
    
    --- result --
    
    The alpha in bravo falls mainly on the charlie!
    
    

Example02

  • example02 string concat with numeric formatting
  • follows the same syntax as sprintf in other languages

    
    {{ "The %04d in %04d falls mainly on the %s!"|format(2,3,'tree') }}
    
    --- result --
    
    The 0002 in 0003 falls mainly on the tree!
    
    

See also


The "{{ ... }}"-delimiter can also be used within strings:

"http://{{ app.request.host }}"

You can use ~ like {{ foo ~ 'inline string' ~ bar.fieldName }}

But you can also create your own concat function to use it like in your question:
{{ concat('http://', app.request.host) }}:

In src/AppBundle/Twig/AppExtension.php

<?php

namespace AppBundle\Twig;

class AppExtension extends \Twig_Extension
{
    /**
     * {@inheritdoc}
     */
    public function getFunctions()
    {
        return [
            new \Twig_SimpleFunction('concat', [$this, 'concat'], ['is_safe' => ['html']]),
        ];
    }

    public function concat()
    {
        return implode('', func_get_args())
    }

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return 'app_extension';
    }
}

In app/config/services.yml:

services:
    app.twig_extension:
        class: AppBundle\Twig\AppExtension
        public: false
        tags:
            - { name: twig.extension }

To mix strings, variables and translations I simply do the following:

    {% set add_link = '
    <a class="btn btn-xs btn-icon-only" 
       title="' ~ 'string.to_be_translated'|trans ~ '" 
       href="' ~ path('acme_myBundle_link',{'link':link.id})  ~ '">
    </a>
    ' %}

Despite everything being mixed up, it works like a charm.


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 #}

In Symfony you can use this for protocol and host:

{{ app.request.schemeAndHttpHost }}

Though @alessandro1997 gave a perfect answer about concatenation.


{{ ['foo', 'bar'|capitalize]|join }}

As you can see this works with filters and functions without needing to use set on a seperate line.


Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to twig

The CSRF token is invalid. Please try to resubmit the form How can I use break or continue within for loop in Twig template? Call PHP function from Twig template Check if inputs form are empty jQuery Counting the number of elements in array How to use absolute path in twig functions symfony 2 twig limit the length of the text and put three dots Find substring in the string in TWIG How to include CSS file in Symfony 2 and Twig? Twig ternary operator, Shorthand if-then-else

Examples related to string-concatenation

How do I concatenate strings? How do I concatenate strings in Swift? How to set the id attribute of a HTML element dynamically with angularjs (1.x)? C++ String Concatenation operator<< how to use concatenate a fixed string and a variable in Python How do I concatenate strings and variables in PowerShell? Concatenating variables in Bash SQL NVARCHAR and VARCHAR Limits Concatenating string and integer in python PHP string concatenation

Examples related to templating

How to include a sub-view in Blade templates? Passing variables through handlebars partial How to concatenate strings in twig Bash Templating: How to build configuration files from templates with Bash? Is there any way to return HTML in a PHP function? (without building the return value as a string) How to replace ${} placeholders in a text file?