Objectives & prerequisites
- Describe the difference between string manipulation, string concatenation, and string interpolation.
- List three interesting or often-used string manipulation filters.
- Compare string concatenation in PHP vs Twig.
- Compare string interpolation in PHP vs Twig.
- Working with
{{ }}and{% %}tags. - Basic programming concepts (variables, functions, operators)
Overview
To manipulate strings (text) or variables that contain strings, Twig provides a number of built-in filters specifically for working with strings: trimming whitespace, retrieving the length of a string, replacing parts of a string, and so on.
We will review some of the often-used string manipulation filters, and discuss string concatenation (combining two strings into one) and string interpolation (using variables inside strings).
String manipulation filters
You can find all of Twig's built-in filters at https://twig.symfony.com/doc/3.x/filters/index.html. Let's review a few of them.
lower & upper
Converts values to lowercase or uppercase.
Docs
- https://twig.symfony.com/doc/3.x/filters/lower.html
- https://twig.symfony.com/doc/3.x/filters/upper.html
Examples
{{ "I LOVE Twig" | lower }}→ i love twig
{{ "I LOVE Twig" | upper }}→ I LOVE TWIG
capitalize & title
Capitalises a value (make first character uppercase) or convert to title case (make first character of each word uppercase).
Docs
- https://twig.symfony.com/doc/3.x/fiters/capitalize.html
- https://twig.symfony.com/doc/3.x/filters/title.html
Examples
{{ "twig is a template language" | capitalize }}→ Twig is a template language
{{ "twig is a template language" | title }}→ Twig Is A Template Language
first & last
Returns the first / last character of a string.
When used with arrays: returns the first / last element of a sequence or mapping.
Docs
- https://twig.symfony.com/doc/3.x/filters/first.html
- https://twig.symfony.com/doc/3.x/filters/last.html
Examples
{{ "twig is a template language" | first }}→ t
{{ "twig is a template language" | last }}→ e
length
Returns the number of characters in a string, or the number of elements in a sequence or mapping.
This filter is used very often in loops, when you want to perform an operation on every element.
Docs
Examples
{{ "twig is a template language" | length }}→ 27
trim
Removes characters (typically whitespace) from the left or right side of a string.
Arguments
- First argument (optional): character(s) to strip. Defaults to whitespace.
- Second argument (optional): "left" or "right". Defaults to both sides.
Docs
Examples
{% set message = " Long-range scanners have detected a subspace anomaly._" %}
{{ message | trim }}
{{ message | trim('right') }}
{{ message | trim('_') }}Output:
Long-range scanners have detected a subspace anomaly._
Long-range scanners have detected a subspace anomaly._
Long-range scanners have detected a subspace anomaly.Explanation:
- Example 1: whitespace (default) trimmed from both sides (default)
- Example 2: whitespace (default) trimmed from the right side
- Example 3: "_" trimmed from both sides (default)
join
Combines elements of a sequence into one string.
Arguments
If no arguments are given, all values "stick together" without separation.
- First optional argument: string to use as a separator.
- Second optional argument: spacer string to use before the last element.
Docs
https://twig.symfony.com/doc/3.x/filters/join.html
Examples
{%
set cities = [ 'Luanda', 'Wellington', 'La Paz', 'Zagreb', 'New Delhi' ]
%}
joined without arguments:
{{ cities | join }}
joined with one single-character argument:
{{ cities | join('-') }}
joined with one string argument:
{{ cities | join(' - ') }}
joined with two arguments:
{{ cities | join(', ', ', and ') }}Output:
joined without arguments:
LuandaWellingtonLa PazZagrebNew Delhi
joined with one single-character argument:
Luanda-Wellington-La Paz-Zagreb-New Delhi
joined with one string argument:
Luanda - Wellington - La Paz - Zagreb - New Delhi
joined with two arguments:
Luanda, Wellington, La Paz, Zagreb, and New DelhiThe last example with two arguments may need a short explanation:
- first argument:
', '(a string consisting of a comma and a space) - second argument:
', and '(string consisting of a comma, a space, the word "and", and another space), used as the last separator.
replace
Replaces placeholders in a string. Anything can be defined as a placeholder.
Docs
Examples
{%
set message = "You have %old old and %new new messages."
%}
{%
set values = {
'%old': 0,
'%new': 42
}
%}
{{ message | replace(values)}}
---
The same operation written in a shorter way:
{{ "You have %old old and %new new messages." | replace({'%old': 0, '%new': 42}) }}Output:
You have 0 old and 42 new messages.
---
The same operation written in a shorter way:
You have 0 old and 42 new messages.Explanation:
The placeholder can be anything you want. You can replace all letters "e" with "o" if you'd like, or use $NUM_OLD instead of %old.
You can replace any string you want, be careful with your placeholders: they must be unique enough to ensure that Twig doesn't replace characters you did not intend to replace.
Here's an example of a badly chosen placeholder:
{# Example of a BADLY CHOSEN PLACEHOLDER: #}
{% set message = "This item from Professor Xavier costs X gold coins." %}
{% set price = { 'X': 1000} %}
{{ message | replace(price) }}Output:
This item from Professor 1000avier costs 1000 gold coins.A quick solution would be to use a placeholder like $X or %X or XCOINS or something else that is guaranteed to be unique inside the string.
date
Formats a date according to a given PHP date format.
Docs
Arguments
- format (optional): the date format to use (defaults to F j, Y H:i)
- timezone (optional): the timezone to use
Examples
Default date format: {{ now | date }}
Day-Month-Year format: {{ now | date("d/m/Y") }}
Year-Month-Day format: {{ now | date("Y-m-d") }}Output:
October 22, 2024 11:32
22/10/2024
2024-10-22Explanation:
- If no date format is provided, the default F j, Y H:i format is used.
Please refer to Twig's date docs for more info and examples, and to the PHP date format docs to learn about all the other formatting options for date/time components.
String concatenation
Putting two strings together is called string concatenation.
In PHP you would use the dot operator (.) to concatenate strings; Twig provides the tilde operator (~)
PHP Example
$first_name = 'Roberto';
$last_name = 'Diaz';
$full_name = $first_name . ' ' . $last_name;
print $full_name;Output:
Roberto DiazTwig Example
{% set first_name = 'Roberto' %}
{% set last_name = 'Diaz' %}
{% set full_name = first_name ~ ' ' ~ last_name %}
{{ full_name }}Output:
Roberto DiazConclusion
Use the tilde operator (~) to concatenate strings in Twig.
String interpolation
String interpolation is the process of embedding strings inside other strings.
PHP
In PHP, there are a few different methods for string interpolation, including:
$output = "Error encountered: $error_message.";
// or
$output = "Error encountered: {$error_message}.";Twig
{% set output = "Error encountered: #{error_message}." %}Conclusion
Use the #{expression} notation for each variable you want to embed inside a string.
Warning
In PHP and Twig, string interpolation is only supported in double-quoted strings ("...").
In both languages single-quoted strings ('...') are always printed as-is, and never evaluated for embedded variables or other special content.
Activity 1
Describe the difference between string concatenation and string interpolation.
Provide a Twig example for each.
Activity 2A
Your template receives the following variables:
var1 = 'stella'var2 = 'artois'
Produce the following output in two different ways. One of your Twig solutions uses a third variable, the other does not.
Stella Artois
Activity 2B
Your template receives the same variables as it did in Activity 1A.
Print both uppercased variables with a space in between and add the first letters (initials) between brackets.
Expected result:
STELLA ARTOIS (SA)Solve in 3 different ways:
- once without concatenation nor interpolation
- once using only one set of
{{ }}delimiters, and using concatenation - once using only one set of
{{ }}delimiters, and using interpolation
Use only the two variables the template receives. Do not declare any additional variables.
Activity 3
Use Twig to print the date "Nov 1, 2024 12:43" in the following formats:
1: November 1, 2024 12:43 or November 1, 2024 12:43
2: 2024-11-01
3: Friday November 1st, 12:43:00
4: 2024-11-01T12:43:00+00:00 (ISO 8601 format)
5: 01/11/2024
6: 11/01/2024
Summary
- Several Twig filters are useful for manipulating strings.
- String concatenation is the process of putting two strings together.
- String interpolation is the process of embedding a string inside another string.
- Use the tilde operator (~) to concatenate strings in Twig.
- Use the #
{expression}notation for each variable you want to embed inside a string.