The following filters are available to Twig templates in Craft:
Filter | Description |
---|---|
abs | Returns the absolute value of a number. |
append | Appends HTML to the end of another element. |
ascii | Converts a string to ASCII characters. |
atom | Converts a date to an ISO-8601 timestamp. |
attr | Modifies an HTML tag’s attributes. |
batch | Batches items in an array. |
camel | Formats a string into camelCase. |
capitalize | Capitalizes the first character of a string. |
column | Returns the values from a single property or key in an array. |
contains | Returns whether an array contains a nested item with a given key/value pair. |
convert_encoding | Converts a string from one encoding to another. |
currency | Formats a number as currency. |
date | Formats a date. |
date_modify | Modifies a date. |
datetime | Formats a date with its time. |
default | Returns the value or a default value if empty. |
duration | Returns a DateInterval object. |
encenc | Encrypts and base64-encodes a string. |
escape | Escapes a string. |
filesize | Formats a number of bytes into something else. |
filterByValue | Filters an array by key/value pairs. |
filter | Filters the items in an array. |
first | Returns the first character/item of a string/array. |
format | Formats a string by replacing placeholders. |
group | Groups items in an array. |
hash | Prefixes a string with a keyed-hash message authentication code (HMAC). |
id | Normalizes an element ID into only alphanumeric characters, underscores, and dashes. |
indexOf | Returns the index of a given value within an array, or the position of a passed-in string within another string. |
index | Indexes the items in an array. |
intersect | Returns the intersecting items of two arrays. |
join | Concatenates multiple strings into one. |
json_decode | JSON-decodes a value. |
json_encode | JSON-encodes a value. |
kebab | Formats a string into “kebab-case”. |
keys | Returns the keys of an array. |
last | Returns the last character/item of a string/array. |
lcfirst | Lowercases the first character of a string. |
length | Returns the length of a string or array. |
literal | Escapes an untrusted string for use with element query params. |
lower | Lowercases a string. |
map | Applies an arrow function to the items in an array. |
markdown | Processes a string as Markdown. |
merge | Merges an array with another array |
multisort | Sorts an array by one or more keys within its sub-arrays. |
namespace | Namespaces input names and other HTML attributes. |
namespaceInputId | Namespaces an element ID. |
namespaceInputName | Namespaces an input name. |
nl2br | Replaces newlines with <br> tags. |
number | Formats a number. |
number_format | Formats numbers. |
parseRefs | Parses a string for reference tags. |
pascal | Formats a string into “PascalCase”. |
percentage | Formats a percentage. |
prepend | Prepends HTML to the beginning of another element. |
purify | Runs HTML code through HTML Purifier. |
raw | Marks as value as safe for the current escaping strategy. |
reduce | Iteratively reduces a sequence or mapping to a single value. |
replace | Replaces parts of a string with other things. |
reverse | Reverses a string or array. |
round | Rounds a number. |
rss | Converts a date to RSS date format. |
slice | Extracts a slice of a string or array. |
snake | Formats a string into “snake_case”. |
sort | Sorts an array. |
spaceless | Removes whitespace between HTML tags. |
split | Splits a string by a delimiter. |
striptags | Strips SGML/XML tags from a string. |
time | Formats a time. |
timestamp | Formats a human-readable timestamp. |
title | Formats a string into “Title Case”. |
translate | Translates a message. |
trim | Strips whitespace from the beginning and end of a string. |
ucfirst | Capitalizes the first character of a string. |
unique | Removes duplicate values from an array. |
upper | Formats a string into “UPPER CASE”. |
url_encode | Percent-encodes a string as a URL segment or an array as a query string. |
values | Returns all the values in an array, resetting its keys. |
withoutKey | Returns an array without the specified key. |
without | Returns an array without the specified element(s). |
Appends HTML to the end of another element.
{{ '<div><p>Lorem</p></div>'|append('<p>Ipsum</p>') }}
{# Output: <div><p>Lorem</p><p>Ipsum</p></div> #}
If you only want to append a new element if one of the same type doesn’t already exist, pass 'keep'
as a second argument.
{{ '<div><p>Lorem</p></div>'|append('<p>Ipsum</p>', 'keep') }}
{# Output: <div><p>Lorem</p></div> #}
If you want to replace an existing element of the same type, pass 'replace'
as a second argument.
{{ '<div><p>Lorem</p></div>'|append('<p>Ipsum</p>', 'replace') }}
{# Output: <div><p>Ipsum</p></div> #}
Converts a string to ASCII characters.
{{ 'über'|ascii }}
{# Output: uber #}
By default, the current site’s language will be used when choosing ASCII character mappings. You can override that by passing in a different locale ID.
{{ 'über'|ascii('de') }}
{# Output: ueber #}
Converts a date to an ISO-8601 timestamp (e.g. 2019-01-29T10:00:00-08:00
), which should be used for Atom feeds, among other things.
{{ entry.postDate|atom }}
Modifies an HTML tag’s attributes, using the same attribute definitions supported by using api:yii\helpers\BaseHtml::renderTagAttributes().
{% set tag = '<div>' %}
{{ tag|attr({
class: 'foo'
}) }}
{# Output: <div class="foo"> #}
Only the first tag will be modified, and any HTML comments or doctype declarations before it will be ignored.
{% set svg %}
<?xml version="1.0" encoding="utf-8"?>
<svg>...</svg>
{% endset %}
{{ svg|attr({
class: 'icon'
}) }}
{# Output:
<?xml version="1.0" encoding="utf-8"?>
<svg class="icon">...</svg> #}
Attributes can be removed by setting them to false
.
{% set tag = '<input type="text" disabled>' %}
{{ tag|attr({
disabled: false
}) }}
{# Output: <input type="text"> #}
class
and style
attributes will be combined with the element’s existing attributes, if set.
{% set tag = '<div class="foo" style="color: black;">' %}
{{ tag|attr({
class: 'bar',
style: {background: 'red'}
}) }}
{# Output: <div class="foo bar" style="color: black; background: red;"> #}
All other attributes will replace the existing attribute values.
{% set tag = '<input type="text">' %}
{{ tag|attr({
type: 'email'
}) }}
{# Output: <input type="email"> #}
If you want to completely replace a class
or style
attribute, remove it first, then set the new value:
{% set tag = '<div class="foo">' %}
{{ tag|attr({class: false})|attr({class: 'bar'}) }}
{# Output: <div class="bar"> #}
Returns a string formatted in “camelCase”.
{{ 'foo bar'|camel }}
{# Output: fooBar #}
Returns the values from a single property or key in the input array.
{% set entryIds = entries|column('id') %}
An arrow function can be passed instead, if the values that should be returned don’t exist as a property or key on the array elements.
{% set authorNames = entries|column(e => e.author.fullName) %}
This works similarly to Twig’s core column
filter, except that ArrayHelper::getColumn() is used rather than PHP’s array_column() function.
Returns whether the passed-in array contains any nested arrays/objects with a particular key/attribute set to a given value.
{% set works = craft.entries()
.section('artwork')
.all() %}
{# See if any of the artwork has a mature rating #}
{% if works|contains('rating', 'm') %}
<p class="mature">Some of this artwork is meant for mature viewers.</p>
{% endif %}
Formats a number with a given currency according to the user’s preferred language.
{{ 1000000|currency('USD') }}
{# Output: $1,000,000.00 #}
You can pass stripZeros=true
to remove any fraction digits if the value to be formatted has no minor value (e.g. cents):
{{ 1000000|currency('USD', stripZeros=true) }}
{# Output: $1,000,000 #}
Formats a timestamp or DateTime object.
{{ entry.postDate|date }}
{# Output: Dec 20, 1990 #}
You can customize how the date is presented by passing a custom date format, just like Twig’s core date
filter:
{{ 'now'|date('m/d/Y') }}
{# Output: 12/20/1990 #}
Craft also provides some special format keywords that will output locale-specific date formats:
Format | Example |
---|---|
short |
12/20/1990 |
medium (default) |
Dec 20, 1990 |
long |
December 20, 1990 |
full |
Thursday, December 20, 1990 |
{{ entry.postDate|date('short') }}
{# Output: 12/20/1990 #}
The current application locale will be used by default. If you want to format the date for a different locale, use the locale
argument:
{{ entry.postDate|date('short', locale='en-GB') }}
{# Output: 20/12/1990 #}
You can customize the timezone the time is output in, using the timezone
param:
{{ entry.postDate|date('short', timezone='UTC') }}
{# Output: 12/21/1990 #}
::: tip
If the value passed to the date filter is null
, it will return the current date by default.
:::
Formats a timestamp or DateTime object, including the time of day.
{{ entry.postDate|datetime }}
{# Output: Dec 20, 1990, 5:00:00 PM #}
Craft provides some special format keywords that will output locale-specific date and time formats:
{{ entry.postDate|datetime('short') }}
{# Output: 9/26/2018, 5:00 PM #}
Possible format
values are:
Format | Example |
---|---|
short |
12/20/1990, 5:00 PM |
medium (default) |
Dec 20, 1990, 5:00:00 PM |
long |
December 20, 1990 at 5:00:00 PM PDT |
full |
Thursday, December 20, 1990 at 5:00:00 PM PDT |
The current application locale will be used by default. If you want to format the date and time for a different locale, use the locale
argument:
{{ entry.postDate|datetime('short', locale='en-GB') }}
{# Output: 20/12/1990, 17:00 #}
You can customize the timezone the time is output in, using the timezone
param:
{{ entry.postDate|datetime('short', timezone='UTC') }}
{# Output: 12/21/1990, 12:00 AM #}
Runs a DateInterval object through api:craft\helpers\DateTimeHelper::humanDurationFromInterval()
<p>Posted {{ entry.postDate.diff(now)|duration(false) }} ago.</p>
Encrypts and base64-encodes a string.
{{ 'secure-string'|encenc }}
Formats a number of bytes into something nicer.
{{ asset.size }}
{# Output: 1944685 #}
{{ asset.size|filesize }}
{# Output: 1.945 MB #}
Filters elements of an array.
If nothing is passed to it, any “empty” elements will be removed.
{% set array = ['foo', '', 'bar', '', 'baz'] %}
{% set filteredArray = array|filter %}
{# Result: ['foo', 'bar', 'baz'] #}
When an arrow function is passed, this works identically to Twig’s core filter
filter.
{% set array = ['foo', 'bar', 'baz'] %}
{% set filteredArray = array|filter(v => v[0] == 'b') %}
{# Result: ['bar', 'baz'] #}
Runs an array through api:craft\helpers\ArrayHelper::where().
{% set array = { 'foo': 'bar', 'bar': 'baz', 'bat': 'bar' } %}
{{ array|filterByValue(v => v == 'bar') }}
{# Result: { 'foo': 'bar', 'bat': 'bar' } #}
Groups items in an array by a the results of an arrow function.
{% set allEntries = craft.entries.section('blog').all() %}
{% set allEntriesByYear = allEntries|group(e => e.postDate|date('Y')) %}
{% for year, entriesInYear in allEntriesByYear %}
<h2>{{ year }}</h2>
<ul>
{% for entry in entriesInYear %}
<li><a href="{{ entry.url }}">{{ entry.title }}</a></li>
{% endfor %}
</ul>
{% endfor %}
Prefixes the given string with a keyed-hash message authentication code (HMAC), for securely passing data in forms that should not be tampered with.
<input type="hidden" name="foo" value="{{ 'bar'|hash }}">
PHP scripts can validate the value via Security::validateData():
$foo = Craft::$app->request->getBodyParam('foo');
$foo = Craft::$app->security->validateData($foo);
if ($foo !== false) {
// data is valid
}
Formats a string into something that will work well as an HTML input id
, via api:craft\web\View::formatInputId().
{% set name = 'input[name]' %}
<input type="text" name="{{ name }}" id="{{ name|id }}">
Runs an array through ArrayHelper::index().
{% set entries = entries|index('id') %}
Returns the index of a passed-in value within an array, or the position of a passed-in string within another string. (Note that the returned position is 0-indexed.) If no position can be found, -1
is returned instead.
{% set colors = ['red', 'green', 'blue'] %}
<p>Green is located at position {{ colors|indexOf('green') + 1 }}.</p>
{% set position = 'team'|indexOf('i') %}
{% if position != -1 %}
<p>There <em>is</em> an “i” in “team”! It’s at position {{ position + 1 }}.</p>
{% endif %}
Returns an array containing only the values that are also in a passed-in array.
{% set ownedIngredients = [
'vodka',
'gin',
'triple sec',
'tonic',
'grapefruit juice'
] %}
{% set longIslandIcedTeaIngredients = [
'vodka',
'tequila',
'rum',
'gin',
'triple sec',
'sweet and sour mix',
'Coke'
] %}
{% set ownedLongIslandIcedTeaIngredients =
ownedIngredients|intersect(longIslandIcedTeaIngredients)
%}
Returns the JSON representation of a value.
This works similarly to Twig’s core json_encode
filter, except that the options
argument will default to JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_QUOT
if the response content type is either text/html
or application/xhtml+xml
.
JSON-decodes a string into an array by passing it through api:yii\helpers\Json::decode().
{% set arr = '[1, 2, 3]'|json_decode %}
Returns a string formatted in “kebab-case”.
::: tip That’s a reference to shish kebabs for those of you that don’t get the analogy. :::
{{ 'foo bar?'|kebab }}
{# Output: foo-bar #}
Lowercases the first character of a string.
{{ 'Foobar'|lcfirst }}
{# Output: foobar #}
Runs a string through api:craft\helpers\Db::escapeParam().
{{ 'SELECT id, * FROM table'|literal }}
{# Output: SELECT id\, \* FROM table #}
Processes a string with Markdown.
{% set content %}
# Everything You Need to Know About Computer Keyboards
The only *real* computer keyboard ever made was famously
the [Apple Extended Keyboard II] [1].
[1]: https://www.flickr.com/photos/gruber/sets/72157604797968156/
{% endset %}
{{ content|markdown }}
This filter supports two arguments:
flavor
can be'original'
(default value),'gfm'
(GitHub-Flavored Markdown),'gfm-comment'
(GFM with newlines converted to<br>
s), or'extra'
(Markdown Extra)inlineOnly
determines whether to only parse inline elements, omitting any<p>
tags (defaults tofalse
)
Sorts an array by one or more properties or keys within an array’s values.
To sort by a single property or key, pass its name as a string:
{% set entries = entries|multisort('title') %}
To sort by multiple properties or keys, pass them in as an array. For example, this will sort entries by their post date first, and then by their title:
{% set entries = entries|multisort(['postDate', 'title']) %}
An arrow function can be passed instead, if the values that should be sorted by don’t exist as a property or key on the array elements.
{% set entries = entries|multisort(e => e.author.fullName) %}
The values will be sorted in ascending order by default. You can switch to descending order with the direction
param:
{% set entries = entries|multisort('title', direction=SORT_DESC) %}
You can also customize which sorting behavior is used, with the sortFlag
param. For example, to sort items numerically, use SORT_NUMERIC
:
{% set entries = entries|multisort('id', sortFlag=SORT_NUMERIC) %}
See PHP’s sort() documentation for the available sort flags.
When sorting by multiple properties or keys, you must set the direction
and sortFlag
params to arrays as well.
{% set entries = entries|multisort([
'postDate',
'title',
], sortFlag=[SORT_NATURAL, SORT_FLAG_CASE]) %}
The |namespace
filter can be used to namespace input names and other HTML attributes.
For example, this:
{% set html %}
<input id="title" name="title" type="text">
{% endset %}
{{ html|namespace('foo') }}
would become this:
<input id="foo-title" name="foo[title]" type="text">
Notice how the id
attribute changed from title
to foo-title
, and the name
attribute changed from title
to foo[title]
.
Namepaces an element ID.
For example, this:
{{ 'bar'|namespaceInputId('foo') }}
would output:
foo-bar
::: tip If this is used within a namespace tag, the namespace applied by the tag will be used by default. :::
Namepaces an input name.
For example, this:
{{ 'bar'|namespaceInputName('foo') }}
would output:
foo[bar]
::: tip If this is used within a namespace tag, the namespace applied by the tag will be used by default. :::
Formats a number according to the user’s preferred language.
You can optionally pass false
to it if you want group symbols to be omitted (e.g. commas in English).
{{ 1000000|number }}
{# Output: 1,000,000 #}
{{ 1000000|number(false) }}
{# Output: 1000000 #}
Parses a string for reference tags.
{% set content %}
{entry:blog/hello-world:link} was my first blog post. Pretty geeky, huh?
{% endset %}
{{ content|parseRefs|raw }}
Returns a string formatted in “PascalCase” (AKA “UpperCamelCase”).
{{ 'foo bar'|pascal }}
{# Output: FooBar #}
Formats a percentage according to the user’s preferred language.
Prepends HTML to the beginning of another element.
{{ '<div><p>Ipsum</p></div>'|prepend('<p>Lorem</p>') }}
{# Output: <div><p>Lorem</p><p>Ipsum</p></div> #}
If you only want to append a new element if one of the same type doesn’t already exist, pass 'keep'
as a second argument.
{{ '<div><p>Ipsum</p></div>'|prepend('<p>Lorem</p>', 'keep') }}
{# Output: <div><p>Ipsum</p></div> #}
If you want to replace an existing element of the same type, pass 'replace'
as a second argument.
{{ '<div><p>Ipsum</p></div>'|prepend('<p>Lorem</p>', 'replace') }}
{# Output: <div><p>Lorem</p></div> #}
Runs the given text through HTML Purifier.
{{ user.bio|purify }}
You can specify a custom HTML Purifier config file as well:
{{ user.bio|purify('user_bio') }}
That will configure HTML Purifier based on the settings defined by config/htmlpurifier/user_bio.json
.
Replaces parts of a string with other things.
When a mapping array is passed, this works identically to Twig’s core replace
filter:
{% set str = 'Hello, FIRST LAST' %}
{{ str|replace({
FIRST: currentUser.firstName,
LAST: currentUser.lastName
}) }}
Or you can replace one thing at a time:
{% set str = 'Hello, NAME' %}
{{ str|replace('NAME', currentUser.name) }}
You can also use a regular expression to search for matches by starting and ending the replacement string’s value with forward slashes:
{{ tag.title|lower|replace('/[^\\w]+/', '-') }}
Outputs a date in the format required for RSS feeds (D, d M Y H:i:s O
).
{{ entry.postDate|rss }}
Returns a string formatted in “snake_case”.
{{ 'foo bar'|snake }}
{# Output: foo_bar #}
Outputs the time of day for a timestamp or DateTime object.
{{ entry.postDate|time }}
{# Output: 10:00:00 AM #}
Craft provides some special format keywords that will output locale-specific time formats:
{{ entry.postDate|time('short') }}
{# Output: 10:00 AM #}
Possible format
values are:
Format | Example |
---|---|
short |
5:00 PM |
medium (default) |
5:00:00 PM |
long |
5:00:00 PM PDT |
The current application locale will be used by default. If you want to format the date and time for a different locale, use the locale
argument:
{{ entry.postDate|time('short', locale='en-GB') }}
{# Output: 17:00 #}
You can customize the timezone the time is output in, using the timezone
param:
{{ entry.postDate|time('short', timezone='UTC') }}
{# Output: 12:00 AM #}
Formats a date as a human-readable timestamp, via api:craft\i18n\Formatter::asTimestamp().
{{ now|timestamp }}
{# Output: 9:00:00 AM #}
Translates a message with Craft::t().
{{ 'Hello world'|t('myCategory') }}
If no category is specified, it will default to site
.
{{ 'Hello world'|t }}
::: tip See Static Message Translations for a full explanation on how this works. :::
Capitalizes the first character of a string.
{{ 'foobar'|ucfirst }}
{# Output: Foobar #}
Runs an array through array_unique().
{% set array = ['Larry', 'Darryl', 'Darryl'] %}
{{ array|unique }}
{# Result: ['Larry', 'Darryl'] #}
Returns an array of all the values in a given array, but without any custom keys.
{% set arr1 = {foo: 'Foo', bar: 'Bar'} %}
{% set arr2 = arr1|values %}
{# arr2 = ['Foo', 'Bar'] #}
Returns an array without the specified element(s).
{% set entries = craft.entries.section('articles').limit(3).find %}
{% set firstEntry = entries[0] %}
{% set remainingEntries = entries|without(firstEntry) %}
Returns an array without the specified key.
{% set array = {
foo: 'foo',
bar: 'bar',
baz: 'baz'
} %}
{% set filtered = array|withoutKey('baz') %}