Filters
Filters in Twig are used to modify the output of variables or expressions. They are an essential feature, allowing you to format data, transform strings, and perform other manipulations directly within your templates. On ShopWired, filters are applied using the pipe |
character.
Common Filters in Twig 1
|upper
The upper
filter converts a string to uppercase.
{{ "hello world" | upper }}
Output: HELLO WORLD
|lower
The lower
filter converts a string to lowercase.
{{ "HELLO WORLD" | lower }}
Output: hello world
|title
The title
filter capitalises the first letter of each word in a string.
{{ "hello world" | title }}
Output: Hello World
|length
The length
filter returns the length of a string, array, or object.
{{ "hello" | length }}
Output: 5
|default
The default
filter provides a fallback value if the variable is undefined or empty.
{{ global.customer.first_name | default('Guest') }}
Output: Guest
(if global.customer.first_name
is undefined)
|date
The date
filter formats a date according to a given format.
{{ "now" | date("Y-m-d") }}
Output: The current date in YYYY-MM-DD
format.
|replace
The replace
filter replaces occurrences of a substring with another string.
{{ "hello world" | replace({"world": "Twig"}) }}
Output: hello Twig
|join
The join
filter joins elements of an array into a string, with an optional separator.
{% set products = ['Nike Trainers', 'Adidas Trainers', 'Versace Trainers'] %}
{{ products | join(', ') }}
Output: Nike Trainers, Adidas Trainers, Versace Trainers
|escape
The escape
filter escapes HTML characters to prevent XSS attacks. This is particularly important when outputting user-generated content.
{{ "<strong>hello</strong>" | escape }}
Output: <strong>hello</strong>
|raw
The raw
filter disables auto-escaping for a specific output. Use this filter carefully, especially with user-generated content, as it can expose your site to XSS vulnerabilities.
{{ "<strong>hello</strong>" | raw }}
Output: <strong>hello</strong>