Twig Filters & Functions

Although Twig already provides an extensive list of filters, functions, and tags, Grav also provides a selection of useful additions to make the process of theming easier.

Grav Twig Filters

Twig filters are applied to Twig variables by using the | character then the filter name. Parameters can be passed in just like Twig functions using parenthesis.

Absolute URL

Take a relative path and convert it to an absolute URL format including hostname

'<img src="/some/path/to/image.jpg" />'|absolute_url <img src="" />

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

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


Return the basename of a path.

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


Converts a string into "CamelCase" format

'send_email'|camelize SendEmail

Chunk Split

Splits a string into smaller chunks of a certain sizeOf



Determine if a particular string contains another string

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


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.


Return the dirname of a path.

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


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


Filters field name by changing dot notation into array notation



Converts a string into a more "human readable" format

'something_text_to_read'|humanize Something text to read


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:

{"first_name": "Guido", "last_name":"Rossum"}|json_decode


Sort an array map by each key


{% set ritems = {'orange':1, 'apple':2, 'peach':3}|ksort %}
{% for key, value in ritems %}{{ key }}:{{ value }}, {% endfor %}

apple:2, orange:1, peach:3,

Left Trim

'/strip/leading/slash/'|ltrim('/') strip/leading/slash/

Removes trailing spaces at the beginning of a string. It can also remove other characters by setting the character mask (see


Take an arbitrary string containing markdown and convert it to HTML using the markdown parser of Grav

'something with **markdown** and [a link]('|markdown

something with markdown and a link


Creates an md5 hash for the string

'anything'|md5 f0e166dc34d14d6c228ffac576c9a43c


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


Converts an integer number of days into the number of months

'181'|monthize 6

Nice Time

Output a date in a human readable nice time format|nicetime(false) 1 day ago


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

'10'|ordinalize 10th


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

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


Converts a string to the English plural version

'person'|pluralize people


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


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

one, two, ten, seven, eight, five, three, six, nine, four,

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.

Right Trim

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


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.


Usage example with a mailto link:

<a href="">
  Email me

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 an array map by a particular key


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


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


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 multi-language support. Please refer to the multi-language documentation for more detailed information.

Translate Admin

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.

Translate Array

Translates an array with a language use the |ta filter. See the multi-language documentation for a detailed example.

'MONTHS_OF_THE_YEAR'|ta(|date('n') - 1) September

Translate language

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



Converts a string to "Title Case" format

'welcome page'|titleize Welcome Page

Trimming a String

You can left-trim and right-trim a string with the following two filters:

'/this/is/a/path/'|ltrim('/') this/is/a/path/

'/this/is/a/path/'|rtrim('/') /this/is/a/path

Truncate a String

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) one s…

Simply truncates to 5 characters.

'one sentence. two sentences'|truncate(5, true) one sentence.

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:

'<p>one <strong>sentence<strong>. two sentences</p>'|striptags|truncate(5) one s…

Specialized versions:


Truncate text by number of characters in a "word-safe" manner.


Truncate HTML by number of characters. not "word-safe"!


Truncate HTML by number of characters in a "word-safe" manner.


Converts a string into "under_scored" format

'CamelCased'|underscorize camel_cased

Twig Functions

Twig functions are called directly with any parameters being passed in via parenthesis.


Cast a value to array



The array_key_value function allows you to add a key/value pair to an associate array

{% set my_array = {fruit: 'apple'} %}
{% set my_array = array_key_value('meat','steak', my_array) %}
{{ print_r(my_array)}}

outputs: Array ( [fruit] => apple [meat] => steak ) 1


Wrapper for PHP's array_key_exists function that returns whether or not a key exists in an associative array.

{% set my_array = {fruit: 'apple', meat: 'steak'} %}
{{ array_key_exists('meat', my_array) }}

outputs: 1


The array_intersect function provides the intersection of two arrays or Grav collections.

{% set array_1 = {fruit: 'apple', meat: 'steak'} %}
{% set array_2 = {fish: 'tuna', meat: 'steak'} %}
{{ print_r(array_intersect(array_1, array_2)) }}

outputs: Array ( [meat] => steak ) 1


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

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


Authorizes an authenticated user to see a resource. Accepts a single permission string or an array of permission strings.

authorize(['admin.statistics', 'admin.super'])


Takes a valid Twig variable and dumps it out into the Grav debugger panel. The debugger must be enabled to see the values in the messages tab.



Same as dump()


The evaluate function can be used to evaluate a string as Twig:


Evaluate Twig

Similar to evaluate, but will evaluate and process with Twig

evaluate_twig({foo: 'bar'}, 'This is a twig variable: {{ foo }}')) This is a twig variable: bar


Output a the EXIF data on an image base on it's filepath. This requires that media.auto_metadata_exif: is enabled in system.yaml

{% set image = page.find('/content/media').media['sample-image.jpg'] %}
{% set data = exif(image.filepath, true) %}
{{ print_r(data)}}


Get Cookie

Retrieve the value of a cookie with this function:



Takes a Github Gist ID and creates appropriate Gist embed code


Is Ajax Request

the isajaxrequest() function can be used to check if HTTP_X_REQUESTED_WITH header option is set:

JSON Decode

You can decode JSON by simply applying this filter:

json_decode({"first_name": "Guido", "last_name":"Rossum"})

Media Directory

Returns a media object for an arbitrary directory. Once obtained you can manipulate images in a similar fashion to pages.


Nonce Field

Generate a Grav security nonce field for a form with a required action:

nonce_field('action') <input type="hidden" name="nonce" value="d177b9188ded320e6284465fa81cc647" />


Parses a path into an array.

{% set parts = pathinfo('/www/htdocs/inc/') %}
{{ print_r(parts) }}

outputs: Array ( [dirname] => /www/htdocs/inc [basename] => [extension] => php [filename] => ) 1

Random String Generation

Will generate a random string of the required number of characters. Particularly useful in creating a unique id or key.

random_string(10) GRDrNVqEIu


Generates an array containging a range of elements, optionally stepped

range(25, 300, 50) Array ( [0] => 25 [1] => 75 [2] => 125 [3] => 175 [4] => 225 [5] => 275 ) 1

Redirect Me

Redirects to a URL of your choosing

redirect_me('', 304)


Will repeat whatever is passed in a certain amount of times.

repeat('blah ', 10) blah blah blah blah blah blah blah blah blah blah


Returns a string from a value. If the value is array, return it json encoded

string(23) => "23" string(['test' => 'x']) => {"test":"x"}


Translate a string, as the |t filter.

t('SITE_NAME') Site Name

Translate Array

Function related to the |ta filter.


Will create a URL and convert any PHP URL streams into a valid HTML resources. A default value can be passed in in case the URL cannot be resolved.

url('theme://images/logo.png')|default('') /user/themes/learn2/images/logo.png


The vardump() function outputs the current variable to the screen (rather than in the debugger as with dump())

{% set my_array = {foo: 'bar', baz: 'qux'} %}
{{ vardump(my_array)}}
array(2) { ["foo"]=> string(3) "bar" ["baz"]=> string(3) "qux" }