Twig filters are applied to Twig variables by using the | character followed by the filter name. Parameters can be passed in just like Twig functions using parenthesis.
absolute_urlTakes an HTML snippet containing a src or href attribute which uses a relative path. Converts the path string to an absolute URL format including hostname.
'<img src="/some/path/to/image.jpg" />'|absolute_url 
array_uniqueWrapper for PHP array_unique() that removes duplicates from an array.
['foo', 'bar', 'foo', 'baz']|array_unique Array
(
[0] => foo
[1] => bar
[3] => baz
)
base32_encodePerforms a base32 encoding on variable
'some variable here'|base32_encode ONXW2ZJAOZQXE2LBMJWGKIDIMVZGK
base32_decodePerforms a base32 decoding on variable
'ONXW2ZJAOZQXE2LBMJWGKIDIMVZGK'|base32_decode some variable here
base64_encodePerforms a base64 encoding on variable
'some variable here'|base64_encode c29tZSB2YXJpYWJsZSBoZXJl
base64_decodePerforms a base64 decoding on variable
'c29tZSB2YXJpYWJsZSBoZXJl'|base64_decode some variable here
basenameReturn the basename of a path.
'/etc/sudoers.d'|basename sudoers.d
camelizeConverts a string into "CamelCase" format
'send_email'|camelize SendEmail
[version=16,17]
chunk_splitSplits a string into smaller chunks of a certain sizeOf
'ONXW2ZJAOZQXE2LBMJWGKIDIMVZGKA'|chunk_split(6, '-') ONXW2Z-JAOZQX-E2LBMJ-WGKIDI-MVZGKA-
[/version]
containsDetermine if a particular string contains another string
'some string with things in it'|contains('things') 1
PHP 7 is getting more strict type checks, which means that passing a value of wrong type may now throw an exception. To avoid this, you should use filters which ensure that the value passed to a method is valid:
stringUse |string to cast value to string.
intUse |int to cast value to integer.
boolUse |bool to cast value to boolean.
floatUse |float to cast value to floating point number.
arrayUse |array to cast value to an array.
definedSometimes you want to check if some variable is defined, and if it's not, provide a default value. For example:
set header_image_width = page.header.header_image_width|defined(900)
This will set the variable header_image_width to the value 900 if it's not defined in the page header.
dirnameReturn the dirname of a path.
'/etc/sudoers.d'|dirname /etc
ends_withTakes a needle and a haystack and determines if the haystack ends with the needle. Also now works with an array of needles and will return true if any haystack ends with the needle.
'the quick brown fox'|ends_with('fox') true
fieldNameFilters field name by changing dot notation into array notation
'field.name'|fieldName field[name]
[version=16,17]
get_typeGets the type of a variable:
page|get_type object
[/version]
humanizeConverts a string into a more "human readable" format
'something_text_to_read'|humanize Something text to read
hyphenizeConverts a string into a hyphenated version.
'Something Text to Read'|hyphenize something-text-to-read
json_decodeYou can decode JSON by simply applying this filter:
array|json_decode
[prism classes="language-twig line-numbers"]
{% set array = '{"first_name": "Guido", "last_name":"Rossum"}'|json_decode %}
{{ print_r(array) }}
[/prism]
[prism classes="language-text"] stdClass Object ( [first_name] => Guido [last_name] => Rossum ) [/prism]
ksortSort an array map by each key
array|ksort
[prism classes="language-twig line-numbers"]
{% set items = {'orange':1, 'apple':2, 'peach':3}|ksort %}
{{ print_r(items) }}
[/prism]
[prism classes="language-text"] Array ( [apple] => 2 [orange] => 1 [peach] => 3 ) [/prism]
ltrim'/strip/leading/slash/'|ltrim('/') strip/leading/slash/
Left trim removes trailing spaces at the beginning of a string. It can also remove other characters by setting the character mask (see https://php.net/manual/en/function.ltrim.php)
markdownTake an arbitrary string containing markdown and convert it to HTML using the markdown parser of Grav. Optional boolean parameter:
true (default): process as block (text mode, content will be wrapped in <p> tags)false: process as line (content will not be wrapped)string|markdown($is_block)
[prism classes="language-twig line-numbers"]
{{'A line with **markdown** and [a link](http://www.cnn.com)'|markdown(false) }}
[/prism]
[prism classes="language-text"] </p> <div class="div"> <p>A paragraph with <strong>markdown</strong> and <a href="http://www.cnn.com">a link</a></p> </div> <p class="paragraph">A line with <strong>markdown</strong> and <a href="http://www.cnn.com">a link</a></p> <p> [/prism]
md5Creates an md5 hash for the string
'anything'|md5 f0e166dc34d14d6c228ffac576c9a43c
modulusPerforms the same functionality as the Modulus % symbol in PHP. It operates on a number by passing in a numeric divider and an optional array of items to select from.
7|modulus(3, ['red', 'blue', 'green']) blue
monthizeConverts an integer number of days into the number of months
'181'|monthize 5
[version=16,17]
nicecronGets a human readable output for cron syntax
"2 * * * *"|nicecron Every hour at 2 minutes past the hour
nicefilesizeOutput a file size in a human readable nice size format
612394|nicefilesize 598.04 KB
nicenumberOutput a number in a human readable nice number format
12430|nicenumber 12.43 k
[/version]
nicetimeOutput a date in a human readable nice time format
page.date|nicetime(false) 8 mos ago
The first argument specifies whether to use a full format date description. It's true by default.
You can provide a second argument of false if you want to remove the time relative descriptor (like 'ago' or 'from now' in your language) from the result.
[version=16,17]
of_typeChecks the type of a variable to the param:
page|of_type('string') false
[/version]
ordinalizeAdds an ordinal to the integer (such as 1st, 2nd, 3rd, 4th)
'10'|ordinalize 10th
padPads a string to a certain length with another character. This is a wrapper for the PHP str_pad() function.
'foobar'|pad(10, '-') foobar----
pluralizeConverts a string to the English plural version
'person'|pluralize people
pluralize also takes an optional numeric parameter which you can pass in when you don't know in advance how many items the noun will refer to. It defaults to 2, so will provide the plural form if omitted. For example:
[prism classes="language-twig "]
We have {{ num_vacancies }} {{ 'vacancy'|pluralize(num_vacancies) }} right now.
[/prism]
[version=16,17]
print_rPrints human-readable information about a variable
page.header|print_r
[prism classes="language-text"] stdClass Object ( [title] => Twig Filters [body_classes] => twig__headers [page-toc] => Array ( [active] => 1 [start] => 3 [depth] => 1 ) [process] => Array ( [twig] => 1 ) [taxonomy] => Array ( [category] => docs ) ) [/prism] [/version]
randomizeRandomizes the list provided. If a value is provided as a parameter, it will skip first n values and keep them in order.
array|randomize
[prism classes="language-twig line-numbers"]
{% set ritems = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']|randomize(2) %}
{{ print_r(ritems) }}
[/prism]
[prism classes="language-text"] Array ( [0] => one [1] => two [2] => five [3] => four [4] => six [5] => nine [6] => eight [7] => ten [8] => seven [9] => three ) [/prism]
regex_replaceA helpful wrapper for the PHP preg_replace() method, you can perform complex Regex replacements on text via this filter:
'The quick brown fox jumps over the lazy dog.'|regex_replace(['/quick/','/brown/','/fox/','/dog/'], ['slow','black','bear','turtle']) The slow black bear jumps over the lazy turtle.
Use the ~-delimiter rather than the /-delimiter where possible. Otherwise you'll most likely have to double-escape certain characters. Eg. ~\/\#.*~ rather than '/\\/\\#.*/', which conforms more closely to the PCRE-syntax used by PHP.
rtrim'/strip/trailing/slash/'|rtrim('/') /strip/trailing/slash
Removes trailing spaces at the end of a string. It can also remove other characters by setting the character mask (see https://php.net/manual/en/function.rtrim.php)
singularizeConverts a string to the English singular version
'shoes'|singularize shoe
safe_emailThe safe email filter converts an email address into ASCII characters to make it harder for email spam bots to recognize and capture.
"someone@domain.com"|safe_email someone@domain.com
Usage example with a mailto link:
[prism classes="language-html line-numbers"] Email me [/prism]
You might not notice a difference at first, but examining the page source (not using the Browser Developer Tools, the actual page source) will reveal the underlying characters encoding.
sort_by_keySort an array map by a particular key
array|sort_by_key
[prism classes="language-twig line-numbers"]
{% set people = [{'email':'fred@yahoo.com', 'id':34}, {'email':'tim@exchange.com', 'id':21}, {'email':'john@apple.com', 'id':2}]|sort_by_key('id') %}
{% for person in people %}{{ person.email }}:{{ person.id }}, {% endfor %}
[/prism]
john@apple.com:2, tim@exchange.com:21, fred@yahoo.com:34,
starts_withTakes a needle and a haystack and determines if the haystack starts with the needle. Also now works with an array of needles and will return true if any haystack starts with the needle.
'the quick brown fox'|starts_with('the') true
titleizeConverts a string to "Title Case" format
'welcome page'|titleize Welcome Page
tTranslate a string into the current language
'MY_LANGUAGE_KEY_STRING'|t 'Some Text in English'
This assumes you have these language strings translated in your site and have enabled -language support. Please refer to the multi-language documentation for more detailed information.
tuTranslate a string into the current language set in the admin interface user preferences
'MY_LANGUAGE_KEY_STRING'|tu 'Some Text in English'
This uses the language field set in the user yaml.
taTranslates an array with a language use the |ta filter. See the multi-language documentation for a detailed example.
'MONTHS_OF_THE_YEAR'|ta(post.date|date('n') - 1) October
tlTranslates a string in a specific language. For more details check out the multi-language documentation.
'SIMPLE_TEXT'|tl(['fr'])
truncateYou can easily generate a shortened, truncated, version of a string by using this filter. It takes a number of characters as the only required field, but has some other options:
'one sentence. two sentences'|truncate(5)|raw one s…
Simply truncates to 5 characters.
'one sentence. two sentences'|truncate(5, true)|raw one sentence.…
The |raw Twig filter should be used with the default … (elipsis) padding element in order for it to render with Twig auto-escaping
Truncates to closest sentence-end after 5 characters.
You can also truncate HTML text, but should first use the |striptags filter to remove any HTML formatting that could get broken if you end between tags:
'<span>one <strong>sentence</strong>. two sentences</span>' |raw|striptags|truncate(25) one sentence. two sentenc…
safe_truncateUse |safe_truncate to truncate text by number of characters in a "word-safe" manner.
truncate_htmlUse |truncate_html to truncate HTML by number of characters. not "word-safe"!
safe_truncate_htmlUse |safe_truncate_html to truncate HTML by number of characters in a "word-safe" manner.
underscorizeConverts a string into "under_scored" format
'CamelCased'|underscorize camel_cased
[version=16,17]
yaml_encodeDump/Encode a variable into YAML syntax
[prism classes="language-twig line-numbers"] {% set array = {foo: [0, 1, 2, 3], baz: 'qux' } %} {{ array|yaml_encode }} [/prism]
[prism classes="language-yaml"] foo: - 0 - 1 - 2 - 3 baz: qux [/prism]
yaml_decodeDecode/Parse a variable from YAML syntax
[prism classes="language-twig line-numbers"] {% set yaml = "foo: [0, 1, 2, 3]\nbaz: qux" %} {{ yaml|yaml_decode|var_dump }} [/prism]
[prism] array(2) { ["foo"]=> array(4) { [0]=> int(0) [1]=> int(1) [2]=> int(2) [3]=> int(3) } ["baz"]=> string(3) "qux" } [/prism] [/version]