Twig Filters

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_url

Takes 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_unique

Wrapper for PHP array_unique() that removes duplicates from an array.

['foo', 'bar', 'foo', 'baz']|array_unique Array ( [0] => foo [1] => bar [3] => baz )

base32_encode

Performs a base32 encoding on variable 'some variable here'|base32_encode ONXW2ZJAOZQXE2LBMJWGKIDIMVZGK

base32_decode

Performs a base32 decoding on variable 'ONXW2ZJAOZQXE2LBMJWGKIDIMVZGK'|base32_decode some variable here

base64_encode

Performs a base64 encoding on variable 'some variable here'|base64_encode c29tZSB2YXJpYWJsZSBoZXJl

base64_decode

Performs a base64 decoding on variable 'c29tZSB2YXJpYWJsZSBoZXJl'|base64_decode some variable here

basename

Return the basename of a path.

'/etc/sudoers.d'|basename sudoers.d

camelize

Converts a string into "CamelCase" format

'send_email'|camelize SendEmail

contains

Determine if a particular string contains another string

'some string with things in it'|contains('things') 1

Casting Values

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:

string

Use |string to cast value to string.

int

Use |int to cast value to integer.

bool

Use |bool to cast value to boolean.

float

Use |float to cast value to floating point number.

array

Use |array to cast value to an array.

defined

Sometimes 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.

dirname

Return the dirname of a path.

'/etc/sudoers.d'|dirname /etc

ends_with

Takes 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

fieldName

Filters field name by changing dot notation into array notation

'field.name'|fieldName field[name]

humanize

Converts a string into a more "human readable" format

'something_text_to_read'|humanize Something text to read

hyphenize

Converts a string into a hyphenated version.

'Something Text to Read'|hyphenize something-text-to-read

json_decode

You can decode JSON by simply applying this filter:

array|json_decode

{% set array = '{"first_name": "Guido", "last_name":"Rossum"}'|json_decode %}
{{ print_r(array) }}

stdClass Object
(
    [first_name] => Guido
    [last_name] => Rossum
)

ksort

Sort an array map by each key

array|ksort

{% set items = {'orange':1, 'apple':2, 'peach':3}|ksort %}
{{ print_r(items) }}

Array
(
    [apple] => 2
    [orange] => 1
    [peach] => 3
)

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)

markdown

Take 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)

<div class="div">
{{ 'A paragraph with **markdown** and [a link](http://www.cnn.com)'|markdown }}
</div>

<p class="paragraph">{{'A line with **markdown** and [a link](http://www.cnn.com)'|markdown(false) }}</p>

</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>

md5

Creates an md5 hash for the string

'anything'|md5 f0e166dc34d14d6c228ffac576c9a43c

modulus

Performs 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

monthize

Converts an integer number of days into the number of months

'181'|monthize 5

nicetime

Output a date in a human readable nice time format

page.date|nicetime(false) 2 yrs 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.

ordinalize

Adds an ordinal to the integer (such as 1st, 2nd, 3rd, 4th)

'10'|ordinalize 10th

pad

Pads a string to a certain length with another character. This is a wrapper for the PHP str_pad() function.

'foobar'|pad(10, '-') foobar----

pluralize

Converts 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:

<p>We have {{ num_vacancies }} {{ 'vacancy'|pluralize(num_vacancies) }} right now.</p>

randomize

Randomizes the list provided. If a value is provided as a parameter, it will skip first n values and keep them in order.

array|randomize

{% set ritems = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']|randomize(2) %}
{{ print_r(ritems) }}

Array
(
    [0] => one
    [1] => two
    [2] => six
    [3] => ten
    [4] => five
    [5] => four
    [6] => three
    [7] => eight
    [8] => seven
    [9] => nine
)

regex_replace

A 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)

singularize

Converts a string to the English singular version

'shoes'|singularize shoe

safe_email

The safe email filter converts an email address into ASCII characters to make it harder for email spam bots to recognize and capture.

"[email protected]"|safe_email someone@domain.com

Usage example with a mailto link:

<a href="mailto:{{ '[email protected]'|safe_email }}">
  Email me
</a>

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_key

Sort an array map by a particular key

array|sort_by_key

{% set people = [{'email':'[email protected]', 'id':34}, {'email':'[email protected]', 'id':21}, {'email':'[email protected]', 'id':2}]|sort_by_key('id') %}
{% for person in people %}{{ person.email }}:{{ person.id }}, {% endfor %}

[email protected]:2, [email protected]:21, [email protected]:34,

starts_with

Takes 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

titleize

Converts a string to "Title Case" format

'welcome page'|titleize Welcome Page

t

Translate 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.

tu

Translate 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.

ta

Translates 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) March

tl

Translates a string in a specific language. For more details check out the multi-language documentation.

'SIMPLE_TEXT'|tl(['fr'])

truncate

You 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 &hellip; (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…

Specialized versions:

safe_truncate

Use |safe_truncate to truncate text by number of characters in a "word-safe" manner.

truncate_html

Use |truncate_html to truncate HTML by number of characters. not "word-safe"!

safe_truncate_html

Use |safe_truncate_html to truncate HTML by number of characters in a "word-safe" manner.

underscorize

Converts a string into "under_scored" format

'CamelCased'|underscorize camel_cased

Found errors? Think you can improve this documentation? Simply click the Edit link at the top of the page, and then the icon on Github to make your changes.

Results