Filters
abs
The abs
filter is used to obtain the absolute value of a number, ensuring the result is always non-negative.
Usage Example:
Given a variable with the value -5
:
{% set number = -5 %}
{{ number|abs }}
This will output: 5
Explanation:
The
abs
filter converts negative numbers to their positive counterparts.For non-negative numbers, the value remains unchanged.
batch
The batch
filter is a handy tool that allows for the grouping of items into smaller lists or "batches" of a specified size. When the number of items isn't a multiple of the batch size, you can provide a second parameter to fill in any missing items.
Usage Example:
Given a list of items:
{% set names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve', 'Frank', 'Grace'] %}
To group these items into batches of 3, with the phrase 'No item' as a filler:
{% for group in names|batch(3, 'N/A') %}
Group:
{% for name in group %}
{{ name }},
{% endfor %}
---
{% endfor %}
Rendered Output:
Group:
Alice, Bob, Charlie,
---
Group:
David, Eve, Frank,
---
Group:
Grace, N/A, N/A,
---
Filter Arguments:
size: Specifies the number of items in each batch. If provided with fractional numbers, it rounds them up.
fill: This parameter fills in any gaps when the total number of items isn't a perfect multiple of the batch size.
preserve_keys: A boolean to determine whether or not to preserve the original item keys. If not provided, the default behavior is not to preserve the keys.
capitalize
The capitalize
filter is used to adjust the casing of strings. When applied, it ensures that the first character of the string is in uppercase and all subsequent characters are in lowercase.
Usage Example:
Given a string with mixed casing:
{{ 'hELlO wOrlD'|capitalize }}
This will produce:
Hello world
It's especially useful for standardizing text inputs or ensuring consistent display of text in your templates.
column
The column
filter is a handy way to extract values from a specific column in a multi-dimensional array or an array of objects. This is especially useful when you need to fetch all values of a particular attribute or key from a list of similar objects or associative arrays.
Usage Example:
Suppose you have a list of items, each with a 'fruit' attribute:
{% set items = [
{ 'fruit' : 'apple', 'color' : 'red' },
{ 'fruit' : 'orange', 'color' : 'orange' },
{ 'fruit' : 'banana', 'color' : 'yellow' }
] %}
{% set fruits = items|column('fruit') %}
Using the column
filter, you can extract all the fruit names into a new list:
fruits will contain ['apple', 'orange', 'banana']
convert_encoding
When working with different character encodings, especially in multi-language environments, you might need to convert strings from one character encoding to another. The convert_encoding
filter comes to the rescue in such cases, making it easy to switch between character sets.
Usage Example:
Suppose you have Japanese text in the iso-2022-jp
character encoding, and you want to display it on a website that uses the UTF-8
encoding. Here's how you can achieve this:
{% set japaneseText = 'Some text in iso-2022-jp encoding' %}
{{ japaneseText|convert_encoding('UTF-8', 'iso-2022-jp') }}
This will convert the string from iso-2022-jp
to UTF-8
, making it suitable for rendering on a standard web page.
date
The date
filter is an indispensable tool to format date values.
Basic Usage:
To format a date to a specific format, use:
{{ post_published_at|date("m/d/Y") }}
Example to show the current date:
{{ "now"|date("m/d/Y") }}
Escaping Characters in Format:
To escape certain characters in your date format:
{{ post_published_at|date("F jS \\a\\t g:ia") }}
Handling Null Values:
By default, if a null value is passed, the filter returns the current date. To output an empty string for null values:
{{ post_published_at is empty ? "" : post_published_at|date("m/d/Y") }}
Default Format:
If no specific format is provided the template engine defaults to F j, Y H:i
for dates
Timezones:
You can specify a timezone:
{{ post_published_at|date("m/d/Y", "Europe/Paris") }}
Arguments Used:
format
: Specifies the date formattimezone
: Determines the timezone for the date
date_modify
The date_modify
filter offers the capability to alter dates based on a specific modifier string.
Basic Usage:
You can modify a date using this filter, and here's an example of pushing a date by one day:
{{ post_published_at|date_modify("+1 day")|date("m/d/Y") }}
Furthermore, it can be efficiently combined with the date
filter to handle formatting.
Arguments:
modifier
: This is the crucial argument which defines how the date should be modified.
default
The default
filter lets you specify a fallback value which is used when the primary variable is either undefined or empty.
Basic Usage:
The random
function generates a random value, which varies based on the provided argument's type:
If
var
is undefined or empty, use the fallback:{{ var|default('var is not defined') }}
If the
foo
item invar
is undefined or empty, use the fallback:{{ var.foo|default('foo item on var is not defined') }}
Accessing array data and providing a default if the
foo
key invar
is not present:{{ var['foo']|default('foo item on var is not defined') }}
If the passed variable is an empty string, it returns the fallback:
{{ ''|default('passed var is empty') }}
Considerations for Booleans:
Using the default
filter with boolean variables might lead to some unexpected outcomes since false
is evaluated as empty. In such scenarios, it might be preferable to utilize ??
:
{% set foo = false %}
{{ foo|default(true) }} {# This will output true #}
{{ foo ?? true }} {# This will output false #}
Further Reading:
It's recommended to review the documentation regarding the defined
and empty
tests to get a clearer understanding of their semantics.
Arguments:
default
: This is the fallback value that is utilized if the primary variable is undefined or empty.
filter
The filter
filter allows you to sift through sequences or mappings based on a given condition provided by an arrow function. This function defines which elements of the sequence or mapping should be kept.
Basic Usage with Sequences:
Given a sequence of sizes:
{% set sizes = [34, 36, 38, 40, 42] %}
You can filter out the ones greater than 38 and then join them with commas:
{{ sizes|filter(v => v > 38)|join(', ') }}
{# outputs: 40, 42 #}
Integration with the for
Tag:
The filter
filter can be combined with the for
tag to iterate over only the filtered items:
{% for v in sizes|filter(v => v > 38) -%}
{{ v }}
{% endfor %}
{# outputs: 40 42 #}
Usage with Mappings:
Given a mapping of sizes:
{% set sizes = {
xs: 34,
s: 36,
m: 38,
l: 40,
xl: 42,
} %}
You can filter based on both key and value:
{% for k, v in sizes|filter((v, k) => v > 38 and k != "xl") -%}
{{ k }} = {{ v }}
{% endfor %}
{# outputs: l = 40 #}
Notes:
The arrow function can access both the value (
v
in the above examples) and the key (if present) of the sequence or mapping.The context in which the arrow function operates also has access to the current context.
Arguments:
array
: Represents the sequence or mapping to filter.arrow
: Defines the arrow function used for filtering.
first
The first
filter provides the initial element of a sequence, mapping, or string.
Basic Usage with Sequences:
For an array or list, the first
filter returns the first element:
{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}
Usage with Hashes:
With hashes, the first
filter will yield the first value:
{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}
Usage with Strings:
For strings, the first
filter retrieves the first character:
{{ '1234'|first }}
{# outputs 1 #}
format
The format
filter allows you to format a string by substituting placeholders. These placeholders follow the sprintf
notation used in many programming languages.
Example:
Suppose you have a sentence with placeholders and you want to replace them with variable values. Here's how you would use the format
filter:
{{ "I like %s and %s."|format(foo, "bar") }}
If the variable foo
has a value of "foo", the output would be:
I like foo and bar.
Remember, the placement of the placeholders corresponds to the order of the arguments provided to the format
filter.
join
The primary purpose of the join
filter is to concatenate the elements of a sequence into a string.
Basic Usage:
By default, the elements of the sequence are combined without any separator:
{{ [1, 2, 3]|join }}
Output: 123
Custom Separator:
You can define a custom separator using the optional first parameter:
{{ [1, 2, 3]|join('|') }}
Output: 1|2|3
Custom Separator for the Last Pair:
A second parameter can be used to specify a different separator between the last two items of the sequence:
{{ [1, 2, 3]|join(', ', ' and ') }}
Output: 1, 2 and 3
Arguments:
glue
: The primary separator.and
: The separator used for the last pair of sequence items.
json_encode
The json_encode
filter is used to transform a given value into its JSON representation.
Usage:
To encode a value into JSON, simply use:
{{ data|json_encode() }}
keys
The keys
filter is utilized to fetch the keys of an array.
Usage:
If you want to loop through the keys of hash, you can use this filter:
{% for key in variable|keys %}
{{ key }}
{% endfor %}
With this approach, you can iterate over the keys, granting more flexibility when working with hashes.
last
The last
filter is used to retrieve the final "element" from a sequence, a mapping, or a string.
Usage:
For sequences:
{{ [1, 2, 3, 4]|last }}
Output:
4
For hashes:
{{ { a: 1, b: 2, c: 3, d: 4 }|last }}
Output:
4
For strings:
{{ '1234'|last }}
Output:
4
Use the last
filter whenever you need to extract the final element from any data structure.
length
The length
filter gives you the count of items in a sequence or mapping, or the character count of a string.
Usage:
{% if users|length > 10 %}
...
{% endif %}
lower
The lower
filter is used to convert all the characters in a given string to lowercase.
Usage:
{{ 'WELCOME'|lower }}
Output:
welcome
map
The map
filter allows you to apply an arrow function to elements of a sequence or a mapping. The purpose is to transform the values in the sequence or mapping based on the logic provided in the arrow function.
Basic Usage:
When dealing with sequences:
{% set people = [
{first: "Bob", last: "Smith"},
{first: "Alice", last: "Dupond"},
] %}
{{ people|map(p => "#{p.first} #{p.last}")|join(', ') }}
Output:
Bob Smith, Alice Dupond
Usage with Keys:
When working with mappings where keys are significant:
{% set people = {
"Bob": "Smith",
"Alice": "Dupond",
} %}
{{ people|map((value, key) => "#{key} #{value}")|join(', ') }}
Output:
Bob Smith, Alice Dupond
The arrow function in the map
filter can access both the value and the key, and it also has access to the broader context.
Arguments:
arrow: This is the arrow function applied to each item in the sequence or mapping.
By using the map
filter, you can effectively transform the data in sequences or mappings to suit the needs of your display logic.
merge
The merge
filter lets you combine two arrays, appending the values of the second array to the first.
Basic Usage with Sequences:
{% set values = [1, 2] %}
{% set values = values|merge(['apple', 'orange']) %}
Output:
[1, 2, 'apple', 'orange']
New values from the second array are appended at the end of the first array.
Usage with Hashes:
{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}
{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}
Output:
{ 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car' }
When merging hashes, if a key from the second hash already exists in the first hash, its value will be overridden. If the key does not exist, it will be added.
Tip for Ensuring Default Values:
If you wish to ensure certain default values in a hash:
{% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
{% set items = { 'apple': 'unknown' }|merge(items) %}
Output:
{ 'apple': 'fruit', 'orange': 'fruit' }
By reversing the two elements in the merge
call, you can guarantee that the values from the second hash will take precedence.
number_format
The number_format
filter is utilized for formatting numbers.
Basic Usage:
{{ 200.35|number_format }}
Controlling Formatting: You can specify the number of decimal places, the character for the decimal point, and the character for the thousands separator:
{{ 9800.333|number_format(2, '.', ',') }}
Formatting Negative Numbers or Math Calculations: Because of the way the template engine handles operator precedence, when dealing with negative numbers or mathematical operations, you should enclose the operation in parentheses:
{{ -9800.333|number_format(2, '.', ',') }} {# outputs: -9 #}
{{ (-9800.333)|number_format(2, '.', ',') }} {# outputs: -9,800.33 #}
{{ 1 + 0.2|number_format(2) }} {# outputs: 1.2 #}
{{ (1 + 0.2)|number_format(2) }} {# outputs: 1.20 #}
Default Formatting:
If no formatting options are provided, the template engine applies the default:
0 decimal places.
.
as the decimal point.,
as the thousands separator.
You can override the default settings for number_format
by providing the specific parameters in each call.
Arguments:
decimal
: The number of decimal points to display.decimal_point
: The character(s) to use for the decimal point.thousand_sep
: The character(s) to use for the thousands separator.
reduce
The reduce
filter is used to iteratively condense a sequence or a mapping to a single value. This process is achieved using an arrow function. This arrow function takes in the return value of the previous iteration and the current value of the sequence or mapping to generate its result.
Basic Usage:
{% set numbers = [1, 2, 3] %}
{{ numbers|reduce((carry, v) => carry + v) }}
{# output 6 #}
With Initial Value: You can also provide an initial value as a second argument to the reduce
filter. This value is used as the starting point for the reduction.
{{ numbers|reduce((carry, v) => carry + v, 10) }}
{# output 16 #}
It's noteworthy to mention that the arrow function can access the current context.
Arguments:
arrow
: The arrow function used for the reduction.initial
: The initial value that will be used as a starting point for the reduction.
replace
The replace
filter is designed to replace placeholders within a string. The format of the placeholder is flexible and doesn't adhere to a strict convention, making it adaptable for various use cases.
Basic Usage:
{{ "I like %this% and %that%."|replace({'%this%': fruit, '%that%': "oranges"}) }}
{# Assuming the "fruit" variable is set to "apples", #}
{# this would output "I like apples and oranges" #}
Without Conventional Delimiter: You don't have to use a conventional delimiter like %
. You're free to use any format for the placeholders, as demonstrated below:
{{ "I like this and --that--."|replace({'this': fruit, '--that--': "oranges"}) }}
{# This would output "I like apples and oranges" #}
Arguments:
from
: A hash or associative array containing the placeholder values to be replaced.
reverse
The reverse
filter is used to reverse sequences, mappings, or strings.
Basic Usage:
Reversing a sequence:
{% for user in users|reverse %}
...
{% endfor %}
Reversing a string:
{{ '1234'|reverse }}
{# This will output "4321" #}
Preserving Keys:
For sequences and mappings, if you want to reverse and still maintain the original numeric keys, you can pass true
as an argument to the reverse
filter.
Without preserving keys:
{% for key, value in {1: "a", 2: "b", 3: "c"}|reverse %}
{{ key }}: {{ value }}
{%- endfor %}
{# This will output: #}
{# 0: c #}
{# 1: b #}
{# 2: a #}
Preserving keys:
{% for key, value in {1: "a", 2: "b", 3: "c"}|reverse(true) %}
{{ key }}: {{ value }}
{%- endfor %}
{# This will output: #}
{# 3: c #}
{# 2: b #}
{# 1: a #}
Arguments:
preserve_keys
: A boolean value determining whether to preserve keys when reversing a mapping or a sequence.
round
The round
filter is used to round off a number to the specified precision.
Basic Usage:
To round a number:
{{ 42.55|round }}
{# This will output "43" #}
To round a number with a specified precision and method:
{{ 42.55|round(1, 'floor') }}
{# This will output "42.5" #}
Rounding Methods:
common
: Rounds either up or down based on the value. For instance, it rounds 1.5 up to 2 and -1.5 down to -2.ceil
: Always rounds up.floor
: Always rounds down.
Arguments:
precision
: Specifies the precision of rounding. Defaults to 0 if not provided.method
: Defines the method of rounding (i.e.,common
,ceil
, orfloor
). Defaults tocommon
if not provided.
slice
The slice
filter is used to extract a portion of a sequence, a mapping, or a string.
Basic Usage:
To extract a portion of a sequence or a string:
{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
{# This will iterate over 2 and 3 #}
{% endfor %}
{{ '12345'|slice(1, 2) }}
{# This will output "23" #}
Dynamic Start and Length:
Both the start and the length can be dynamic:
{% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
{# ... #}
{% endfor %}
Syntactic Sugar with [] Notation:
You can use the []
notation as a shorthand:
{% for i in [1, 2, 3, 4, 5][start:length] %}
{# ... #}
{% endfor %}
{{ '12345'[1:2] }} {# This will display "23" #}
Omitting Arguments:
Omitting the first argument assumes it to be
0
:
{{ '12345'[:2] }} {# This will display "12" #}
Omitting the last argument selects everything until the end:
{{ '12345'[2:] }} {# This will display "345" #}
Behavior:
When defining the start:
If positive, the slice begins from that start in the variable.
If negative, the slice begins that far from the end of the variable.
For the length:
If positive, the slice will contain up to that many elements.
If negative, the slice stops that many elements from the end of the variable.
If omitted, it slices everything from the start until the end.
Arguments:
start
: Specifies the start of the slice.length
: Defines the size of the slice.preserve_keys
: A flag indicating whether to maintain keys or not (applicable when the input is an array).
slug
The slug
filter is designed to convert a given string into a safer ASCII representation, primarily for URL-friendly slugs.
Basic Usage:
Here's how you can transform a string with non-ASCII characters and special symbols into a URL-friendly slug:
{{ 'Wôrķšƥáçè ~~sèťtïñğš~~'|slug }}
{# This outputs: "Workspace-settings" #}
Custom Separators:
By default, words in the slug are separated by dashes (-). However, you can choose a custom separator by providing it as an argument:
{{ 'Wôrķšƥáçè ~~sèťtïñğš~~'|slug('/') }}
{# This outputs: "Workspace/settings" #}
Specifying Language:
The slugger tool can automatically determine the language of the original string. Nonetheless, if desired, you can specify the language explicitly with the second argument:
{{ '...'|slug('-', 'ko') }}
Arguments:
separator
: Defines the character that separates the words in the slug. The default is a dash (-).locale
: Sets the locale or language of the original string. If this is not specified, the slugger will attempt to auto-detect it.
sort
The sort
filter is used for sorting arrays.
Basic Usage:
To sort a simple array:
{% for user in users|sort %}
...
{% endfor %}
Advanced Sorting with Arrow Function:
For more intricate sorting scenarios, you can pass an arrow function to customize the sorting mechanism:
{% set fruits = [
{ name: 'Apples', quantity: 5 },
{ name: 'Oranges', quantity: 2 },
{ name: 'Grapes', quantity: 4 },
] %}
{% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
{{ fruit }}
{% endfor %}
This code sorts the fruits based on their quantity and outputs in this order:
Oranges
Grapes
Apples
Note: The spaceship operator (<=>
) simplifies the comparison between values, returning -1, 0, or 1, which is especially handy in sorting functions.
Arguments:
arrow
: An optional arrow function to define custom sorting logic.
spaceless
The spaceless
filter is used to eliminate whitespace between HTML tags, but not within them. It also doesn't touch whitespace in plain text.
Basic Usage:
Here's a simple example:
{{
"<div>
<strong>foo</strong>
</div>
"|spaceless }}
This results in the output:
<div><strong>foo</strong></div>
Combining with the apply
Tag:
For dealing with larger chunks of HTML, you can combine the spaceless
filter with the apply
tag:
{% apply spaceless %}
<div>
<strong>foo</strong>
</div>
{% endapply %}
The outcome remains the same:
<div><strong>foo</strong></div>
split
The split
filter is used to divide a string into multiple parts using a specified delimiter. The result is a list of strings.
Basic Usage:
Consider this example where we split a comma-separated string:
{% set foo = "one,two,three"|split(',') %}
Here, foo
would result in the list:
['one', 'two', 'three']
Using the Limit Argument:
The limit
argument can control the number of splits:
If
limit
is positive, the returned array will have a maximum oflimit
elements. The last element will contain the remaining portion of the string.For a negative
limit
, all parts except the last-limit
are returned.When
limit
is zero, it's treated as 1.
Example:
{% set foo = "one,two,three,four,five"|split(',', 3) %}
The resulting foo
would be:
['one', 'two', 'three,four,five']
Splitting with Empty Delimiter:
If the delimiter is left empty, the string is split into chunks of equal length. The chunk length is determined by the limit
argument, defaulting to one character:
{% set foo = "123"|split('') %}
This results in:
['1', '2', '3']
Another example:
{% set bar = "aabbcc"|split('', 2) %}
Here, bar
would be:
['aa', 'bb', 'cc']
Arguments:
delimiter
: Specifies the character or string to use for splitting.limit
: Determines the number of splits or chunk size.
striptags
The striptags
filter is designed to remove SGML/XML tags from a string. It also condenses consecutive whitespace characters into a single space.
Basic Usage:
For a simple stripping of all HTML tags:
{{ some_html|striptags }}
Preserving Specific Tags:
You have the ability to specify tags that should not be removed:
{{ some_html|striptags('<br><p>') }}
In the above example, tags like <br/>
, <br>
, <p>
, and </p>
will be retained in the string while others will be removed.
Arguments:
allowable_tags
: List of tags that shouldn't be stripped.
timezone_name
The timezone_name
filter takes a timezone identifier and returns its localized name.
Basic Usage:
For Central European Time (Paris):
{{ 'Europe/Paris'|timezone_name }}
For Pacific Time (Los Angeles):
{{ 'America/Los_Angeles'|timezone_name }}
Specifying a Locale:
By default, the filter determines the name based on the current locale. However, you can provide a specific locale to override this default:
In French, for Pacific Time (Los Angeles):
{{ 'America/Los_Angeles'|timezone_name('fr') }}
In this case, it would output "heure du Pacifique nord-américain (Los Angeles)".
Arguments:
locale
: Desired locale for the timezone name.
title
The title
filter converts a string into its titlecased version, ensuring that each word in the string starts with an uppercase letter while the rest of the characters are in lowercase.
Usage:
{{ 'my first car'|title }}
The above example would output:
My First Car
trim
The trim
filter is used to strip whitespace (or other specified characters) from the beginning and end of a string.
Usage:
Basic trimming of whitespaces:
{{ ' Hello there. '|trim }}
This would output:
Hello there.
Trimming specific characters:
{{ ' Hello there.'|trim('.') }}
This would output:
Hello there
Trimming only from the left side:
{{ ' Hello there. '|trim(side='left') }}
This would output:
Hello there.
Trimming only from the right side:
{{ ' Hello there. '|trim(' ', 'right') }}
This would output:
Hello there.
Arguments:
character_mask
: Specifies which characters should be stripped.side
: Dictates from which side the characters should be stripped. By default, it trims from both the left and the right (both
). But you can specify eitherleft
orright
to strip characters from only one side.
u
The u
filter wraps a text in a Unicode object that provides methods to manipulate the string.
Here are some common use cases:
Wrapping a Text to a Given Number of Characters:
{{ 'Lorem Ipsum Text + Dolor Sit = <3'|u.wordwrap(5) }}
Output:
Lorem
Ipsum
Text
+
Dolor
Sit
= <3
Truncating a String:
{{ 'Lorem ipsum'|u.truncate(8) }}
Output:
Lorem ip
Replacing the last characters:
{{ 'Lorem ipsum'|u.truncate(8, '...') }}
Output:
Lorem...
The truncate
method also accepts a third argument to preserve whole words:
{{ 'Lorem ipsum dolor sit'|u.truncate(10, '...', false) }}
Output:
Lorem ipsum...
Converting a String to snake_case:
{{ 'LoremIpsumTextWithDolorSit'|u.snake }}
Output:
lorem_ipsum_text_with_dolor_sit
Converting a String to camelCase:
{{ 'lorem_ipsum text with dolor_sit'|u.camel.title }}
Output:
IpsumTextWithDolorSit
Chaining Methods:
{{ 'Lorem Ipsum Text + Dolor Sit = <3'|u.wordwrap(5).upper }}
Output:
LOREM
IPSUM
TEXT
+
DOLOR
SIT
= <3
For Large Strings Manipulation, Use the apply Tag:
{% apply u.wordwrap(5) %}
Some large amount of text...
{% endapply %}
upper
The upper
filter converts a value to uppercase:
{{ 'lorem ipsum'|upper }}
Output:
LOREM IPSUM
url_encode
The url_encode
filter percent-encodes a given string for use in a URL segment or an array for use in a query string:
{{ "lorem-ip*sum"|url_encode }}
{# outputs "lorem-ip%2Asum" #}
{{ "string with spaces"|url_encode }}
{# outputs "string%20with%20spaces" #}
{{ {'param1': 'value1', 'param2': 'value2'}|url_encode }}
{# outputs "param1=value1¶m2=value2" #}
Last updated