In this chapter, let's study about Twig Filters and Functions. Filters are used to format the data the way you want with the required output too. Functions are used to generate contents.
Twig templates are text files that contain expressions and variables replaced by values. Twig uses three types of tags.
Output tags − The following syntax is used to display the evaluated expressions result here.
{{ Place Your Output Here }}
Action Tags − The following syntax is used to execute statements here.
{% executable statements are placed here %}
Comment tags − The following syntax is used to write comments in the Twig template file.
{# write your comment here #}
Twig Filters uses the | character to apply filters to Twig variable followed by the filter name. Arguments can be passed in parenthesis similarly like Twig functions.
The following table shows Twig Filters used in Grav −
Sr.No. | Filter & Description | Example |
---|---|---|
1 | Absolute URL It takes the relative path and converts it to an absolute URL. |
'<img src="/some/path/img.jpg"/>' |absolute_url converts to − <img src="http://learn.getGrav.org/some/path/img.jpg" /> |
2 | Camelize It converts a string to CamelCase format. |
'contact_us'| camelize converts to − ContactUs |
3 | Contains if it finds the string. |
'This is some string' | contains('some') the output is − 1 |
4 | Defined You can check if some variable is defined or not. If variable is not defined, you can provide a default value. |
set header_image_width = page.header.header_image_width|defined(900) It sets header_image_width with value 900 if it’s not defined. |
5 | Ends-With You can determine whether a string ends with a given string by using Ends-With filter. |
'this is an example for ends-with filter' | ends_with('filter') it is displayed as − True |
6 | FieldName It filters the field name by changing dot into array notation. |
'field.name'|fieldName it is displayed as − field[name] |
7 | Humanize It is used to convert a string to human readable format. |
'some_text_to_read'|humanize it is displayed as − Some text to read |
8 | Ksort It sorts an array map using key. |
{% set ritems = {'orange':1, 'apple':2, 'peach':3}|ksort %} {% for key, value in ritems %}{{ key }}:{{ value }}, {% endfor %} it is displayed as − apple:2, orange:1, peach:3, |
9 | Left Trim It is used to remove white spaces at the beginning of a string and removes the matching character given from the left side of the string. |
'/strip/leading/slash/'|ltrim('/') it is displayed as − strip/leading/slash/ |
10 | Markdown It is used to convert the string containing markdown into HTML using the markdown parser of Grav. |
'## some text with markdown'|markdown it is displayed as −
|
11 | MD5 The md5 hash for the string can be created by using this filter. |
'something'|md5 it is displayed as − 437b930db84b8079c2dd804a71936b5f |
12 | Monthize By using Monthize filter, we can convert an integer number of days to number of months. |
'61'|monthize it is displayed as − 2 |
13 | Nice Time By using the Nice Time filter, we can get a date in nice human readable time format as output. |
page.date|nicetime(false) it is displayed as − 3 hrs ago |
14 | Ordinalize Ordinals ( like 1st, 2nd, 3rd ) can be given to integers by using Ordinalize filter. |
'78'| ordinalize it is displayed as − 78th |
15 | Pluralize A string can be converted to its plural English form by using Pluralize filter. |
'child'|pluralize it is displayed as − children |
16 | Randomize This filter helps randomize the provided list. If parameter contains any values then those values are skipped from randomizing. |
{% set ritems = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']|randomize(3) %} {% for ritem in ritems %}{{ ritem }}, {% endfor %} it is displayed as − one, two, three, eight, six, five, nine, seven, ten, four, |
17 | Right Trim It is quite similar to left trim except it removes whitespaces and matched character from right side of the string. |
'/strip/leading/slash/'|rtrim('/') it is displayed as − /strip/leading/slash |
18 | Singularize A string can be converted to English singular version by using Singular filter. |
'vehicles'|singularize it is displayed as − vehicle |
19 | Safe Email Safe Email filter is used to convert an email address into ASCII characters so that it makes harder for an email to be spammed. |
"someoneemailaddress@domain.com"|safe_email the output is − someoneemailaddress@domain.com |
20 | SortByKey It is used to sort the array map using keys. |
{% set people = [{'email':'john@gmail.com', 'id':3}, {'email':'melw@fdd.com', 'id':1}, {'email':'nancy@fb.com', 'id':7}]|sort_by_key('id') %} {% for person in people %}{{ person.email }}:{{ person.id }}, {% endfor %} it displays − melw@fdd.com:1, john@gmail.com:3, nancy@fb.com:7, |
21 | Starts-With You can determine whether a string starts with a given string by using Starts-With filter. |
'this is an example for starts-with filter' |starts_with('this') the output is − true |
22 | Translate for more detailed information. |
MY_LANGUAGE_KEY_STRING it displays − 'Some text in English' |
23 | Translate Admin It translates a string into current language which is set in the user.yaml file. |
|
24 | Titleize A string is converted into Title Case format by using Titleize. |
'welcome page'|titleize it is displayed as − Welcome Page |
25 | UnderScoreize format by using UnderScoreize filter. |
'ContactUs'|underscorize it is converted to − contact_us |
26 | Truncate a string You can use Truncate to truncate a string or shorten the string, you must specify number of characters. |
'one sentence. two sentences'|truncate(5) it truncates to − one s... You can use true as parameter if you don't want to truncate the string to closest sentence-end after the given number of characters. 'one sentence. two sentences'|truncate(5, true) it truncates to − one sentenceYou can also strip HTML text, but you should use striptags filter before truncate filter. '<p>one <strong>sentence<strong>. two sentences</p>'|striptags|truncate(5) it is displayed as − one s |
Twig Functions are directly called by passing the parameter. Following table lists the functions −
Sr.No. | Function & Description | Example |
---|---|---|
1 | Array This function cast a value to array. |
array(value) |
2 | Authorize This function makes an authenticated user is authorized to see a resource and accepts permission string or array of permission strings. |
authorize(['admin.statistics', 'admin.super']) |
3 | Dump It accepts a valid twig variable and dumps it into the Grav debugger panel. However, the debugger should be enabled to see message tab values. |
dump(page.header) |
4 | Debug This works same as the dump() function. |
|
5 | Gist This function creates the Gist embed code based on the Github Gist ID. |
|
6 | Random String Generation This function will create a random string with the specified number of characters. These strings can be used as unique id or key. |
generate_random_string(10) |
7 | Repeat This function will repeat the string for given amount of time. |
repeat('Grav ', 10) will repeat Grav 10 times. |
8 | String Generates a random string of specified character length. |
ta (23) |
9 | Translate Array It is a function connected with |ta filter. |
|
10 | Url This filter will create a URL and it will also convert PHP URL streams into valid HTML resources. If the URL cannot be resolved a default value can be passed. |
url('theme://images/logo.png') | default('http://www.placehold.it/150x100/f4f4f4') |
11 | Translate Using the Translate filter, a string is translated as the |t filter. |
t('SITE_NAME') is translated to − Site Name |