On top of the template filters that Twig comes with, Craft provides a few of its own.
Outputs a date in the ISO-8601 format (which should be used for Atom feeds, among other things).
{{ entry.postDate|atom }}
Returns a string formatted in “camelCase”.
{{ "foo bar"|camel }}
{# Outputs: fooBar #}
Runs an array through ArrayHelper::getColumn() and returns the result.
{% set entryIds = entries|column('id') %}
Formats a number with a given currency according to the user’s preferred language.
If you pass true
into the second argument, the “.00” will be stripped if there’s zero cents.
{{ 1000000|currency('USD') }} => $1,000,000.00
{{ 1000000|currency('USD', true) }} => $1,000,000
Like Twig’s core date
filter, but with additional support for the following format
values:
'short'
'medium'
(default)'long'
'full'
When one of those formats are used, the date will be formatted into a localized date format using craft\i18n\Formatter::asDate().
A translate
argument is also available. If true
is passed, the formatted date will be run through craft\helpers\DateTimeHelper::translateDate() before being returned.
{{ entry.postDate|date('short') }}
Like the date
filter, but the result will also include a timestamp.
{{ entry.postDate|datetime('short') }}
Runs a DateInterval
object through craft\helpers\DateTimeHelper::humanDurationFromInterval()
Encrypts and base64-encodes a string.
{{ "secure-string"|encenc }}
Formats a number of bytes into something nicer.
Removes any empty elements from an array and returns the modified array.
Runs an array through craft\helpers\ArrayHelper::filterByValue().
Groups the items of an array together based on common properties.
{% set allEntries = craft.entries.section('blog').all() %}
{% set allEntriesByYear = allEntries|group('postDate.year') %}
{% 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 CSecurityManager::validateData:
$foo = craft()->request->getPost('foo');
$foo = craft()->security->validateData($foo);
if ($foo !== false) {
// data is valid
}
Formats a string into something that will work well as an HTML input id
, via 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)
%}
Like Twig’s core json_encode
filter, but if the options
argument isn’t set, it 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
.
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 }}
{# Outputs: foo-bar #}
Lowercases the first character of a string.
Runs a string through craft\helpers\Db::escapeParam
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]: http://www.flickr.com/photos/gruber/sets/72157604797968156/
{% endset %}
{{ content|markdown }}
Sorts an array with ArrayHelper::multisort().
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 }} => 1,000,000
{{ 1000000|number(false) }} => 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 }}
{# Outputs: FooBar #}
Formats a percentage according to the user’s preferred language.
Replaces parts of a string with other things.
You can replace multiple things at once by passing in an object of search/replace pairs:
{% 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.name|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 }}
{# Outputs: foo_bar #}
Like the time
filter, but for times rather than dates.
{{ entry.postDate|time('short') }}
Formats a date as a human-readable timestamp, via craft\i18n\Formatter::asTimestamp().
Translates a message with Craft::t(). If no category is specified, it will default to site
.
{{ "Hello world"|t }}
Capitalizes the first character of a string.
Capitalizes the first character of each word in a string.
Runs an array through array_unique().
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) %}