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

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

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.

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

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:

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

Ksort

Sort an array map by each key

array|ksort

{% 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 http://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

'something with **markdown** and [a link](http://www.cnn.com)'|markdown

something with markdown and a link

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

Monthize

Converts an integer number of days into the number of months

'181'|monthize 5

Nice Time

Output a date in a human readable nice time format

page.date|nicetime(false) 7 mos ago

Ordinalize

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

'10'|ordinalize 10th

Pad

Pads a string to a certain lenth 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

Randomize

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

array|randomize

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

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

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 http://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.

"someone@domain.com"|safe_email someone@domain.com

Usage example with a mailto link:

<a href="mailto:your.email@server.com">
  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.

SortByKey

Sort an array map by a particular key

array|sort_by_key

{% 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 %}

john@apple.com:2, tim@exchange.com:21, fred@yahoo.com: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

Translate

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.

Titleize

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:

|safe_truncate

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

|truncate_html

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

|safe_truncate_html

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

Underscoreize

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.

Array

Cast a value to array

array(value)

ArrayKeyValue

Get an item from an associative array. If no array passed, generates a one item associate array:

arrayKeyValue('key', 'value') returns: {key: value}

arrayKeyValue('foo', 'baz', {something: else, foo: bar}) returns: {something: else, foo: baz}

Authorize

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

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

Dump

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.

dump(page.header)

Debug

Same as dump()

Evaluate

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

evaluate('grav.language.getLanguage')

Get Cookie

Retrieve the value of a cookie with this function:

get_cookie('your_cookie_key')

Gist

Takes a Github Gist ID and creates appropriate Gist embed code

gist('bc448ff158df4bc56217')

JSON Decode

You can decode JSON by simply applying this filter:

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

Nonce Field

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

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

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

Repeat

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

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

String

Generates a random string. Pass count to set the characters length.

ta(23)

Translate

Translate a string, as the |t filter.

t('SITE_NAME') Site Name

Translate Array

Function related to the |ta filter.

Url

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('http://www.placehold.it/150x100/f4f4f4') /user/themes/learn2/images/logo.png