65

I want to do something like this:

{% set c=a+b %}

Where a and b are strings.
How can I do it?

Shaunak Shukla
  • 2,347
  • 2
  • 18
  • 29
sh3211
  • 993
  • 3
  • 9
  • 9

4 Answers4

152

The way to do it is:

{% set c = a ~ b %}
Shimon S
  • 4,048
  • 2
  • 29
  • 34
  • How do you concatenate 'some text with a' `stringOrVariable`? – Pathros Mar 02 '16 at 16:00
  • 5
    In PHP we use dot `.` to concatenate strings or variables, in Twig we use `~`. Example: `{{ "Hello" ~ a }}` to concatenate a string and a variable. For variables you can do `{{ a ~ b ~ c }}` The `~` replaces the dot `.` – Anthony Dec 08 '16 at 07:00
20

Use the "~" operator. This will concatenate your two strings. The "+" operator cannot be used to combine strings.

You would get this:

{% set c=a~b %}

More info: The "+" operator: Adds two objects together (the operands are casted to numbers).

Wouter Konecny
  • 3,260
  • 3
  • 19
  • 26
10

You can use:

{{ "Hello " ~ name ~ "!" }}

Atikrant Upadhye
  • 185
  • 2
  • 13
0

A clearer example for the {% block page %}...{% endblock %}:

{% block page %}
    {% set page = page | merge({
    "title"       : branchName,
    "description" : "This description has "~branchName~" as its title"
    }) %}
    {{ parent() }}
{% endblock %}

A clearer example for the {% block content %}...{% endblock %}:

{% block content %}
    This is just a sample string for {{ branchName }} that needs no concatenation
{% endblock %}
The Billionaire Guy
  • 3,382
  • 28
  • 31