Concatenating Strings and Variables in Twig in Drupal 8/9

lakshmi , Credit to  volkotech-solutions Feb 09

Concatenation is the process of joining two strings and variables together. This blog will explain various methods for concatenating strings in a twig template.

Create variables:

Preprocess functions can be used to add new variables to a Twig template file. Implement hook preprocess in  .theme file. Add the following code in themename.theme file.

<?php

/**
* Implements hook_preprocess_page().
*/
function themename_preprocess_page(&$variables) {
//create a variables.
 $variables['first_name'] = 'vijaya';
 $variables['last_name'] = 'lakshmi';
}

Method 1: Using String Interpolation

String interpolation allows any valid expression within a double-quoted string to be used. The expressions are evaluated and then concatenated to the string. Add the following code in page.html.twig file.

{{ "#{first_name} #{last_name}!" }}
{# output: vijaya lakshmi! #}


{{ "#{first_name} #{last_name}!" | title }}
{# output: Vijaya Lakshmi! #}


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

Method 2: Using the ~ (Tilde) Operator

The tilde character joins all operands (strings and/or variables) together to form a single string. Add the following code in page.html.twig file.

{{ first_name ~ ' ' ~ last_name ~ '!' }}
{# output: vijaya lakshmi! #}

{{ first_name|upper ~ ' ' ~ last_name ~ '!' }}
{# output: VIJAYA lakshmi! #}

{{ (first_name ~ ' ' ~ last_name ~ '!') | title }}
{# output: Vijaya Lakshmi! #}

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

Method 3: Using the format Filter

Twig's format filter is the same as PHP's sprintf notation. It formats a string by replacing the placeholders it contains. Add the following code in page.html.twig file.

{{ "%s %s!" | format(first_name, last_name) }}
{# output: vijaya lakshmi! #}

{{ "%s %s!" | format(first_name, last_name) | title }}
{# output: Vijaya Lakshmi! #}

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

Method 4: Joining an Array of Strings With join

An array of strings can be joined together to form a single string. Add the following code in page.html.twig file.

{{ [first_name, ' ', last_name, '!'] | join }}
{# output: vijaya lakshmi! #}

{{ [first_name|upper, ' ', last_name, '!'] | join }}
{# output: VIJAYA lakshmi! #}

{{ [first_name, ' ', last_name, '!'] | join | title }}
{# output: Vijaya Lakshmi! #}

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

Conclusion:

These are the various methods for concatenating strings in a twig template. I hope you found this blog to be helpful.

 

Comments