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 <img src="https://learn.getgrav.org/some/path/to/image.jpg">

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

chunk_split

Splits a string into smaller chunks of a certain sizeOf

'ONXW2ZJAOZQXE2LBMJWGKIDIMVZGKA'|chunk_split(6, '-') ONXW2Z-JAOZQX-E2LBMJ-WGKIDI-MVZGKA-

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]

get_type

Gets the type of a variable:

page|get_type object

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

nicecron

Gets a human readable output for cron syntax

"2 * * * *"|nicecron Every hour at 2 minutes past the hour

nicefilesize

Output a file size in a human readable nice size format

612394|nicefilesize 598.04 KB

nicenumber

Output a number in a human readable nice number format

12430|nicenumber 12.43 k

nicetime

Output a date in a human readable nice time format

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

of_type

Checks the type of a variable to the param:

page|of_type('string') false

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>

Prints human-readable information about a variable

page.header|print_r

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
        )

    [metadata] => Array
        (
            [description] => Grav documentation
            [generator] => GravCMS
            [title] => Twig Filters
            [keywords] => 
            [image] => https://learn.getgrav.org/16/themes/twig-tags-filters-functions/filters/seomagic-image
            [robots] => all
            [fb:app_id] => 
            [og:url] => https://learn.getgrav.org/16/themes/twig-tags-filters-functions/filters
            [og:site_name] => Grav Documentation
            [og:title] => Twig Filters
            [og:description] => Grav documentation
            [og:type] => article
            [og:image] => https://learn.getgrav.org/16/themes/twig-tags-filters-functions/filters/seomagic-image
            [og:image:width] => 1200
            [og:image:height] => 630
            [og:image:secure] => https://learn.getgrav.org/16/themes/twig-tags-filters-functions/filters/seomagic-image
            [twitter:card] => summary_large_image
            [twitter:site] => 
            [twitter:title] => Twig Filters
            [twitter:description] => Grav documentation
            [twitter:image] => https://learn.getgrav.org/16/themes/twig-tags-filters-functions/filters/seomagic-image
            [twitter:image:alt] => Twig Filters
        )

)

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] => three
    [3] => four
    [4] => six
    [5] => ten
    [6] => nine
    [7] => seven
    [8] => five
    [9] => eight
)

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

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

yaml_encode

Dump/Encode a variable into YAML syntax

{% set array = {foo: [0, 1, 2, 3], baz: 'qux' } %}
{{ array|yaml_encode }}

foo:
  - 0
  - 1
  - 2
  - 3
baz: qux

yaml_decode

Decode/Parse a variable from YAML syntax

{% set yaml = "foo: [0, 1, 2, 3]\nbaz: qux" %}
{{ yaml|yaml_decode|var_dump }}

array(2) {
  ["foo"]=>
  array(4) {
    [0]=>
    int(0)
    [1]=>
    int(1)
    [2]=>
    int(2)
    [3]=>
    int(3)
  }
  ["baz"]=>
  string(3) "qux"
}

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