In this chapter let's study about Twig Filters and Functions. Filters are used to format the data the way you want and output. 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.
Following table shows Twig Filters used in Grav:
Twig templates are text files that contain expressions and variables replaced by values. Twig uses three types of tags.
- Output tags: It is used to display evaluated expressions result. It uses below syntax.
{{ Place Your Output Here }}
- Action Tags: It is used to execute statements. It uses below syntax.
{% executable statements are placed here %}
- Comment tags: It is used to write comments in Twig template file. It uses below syntax.
{# write your comment here #}
Twig Filters
Twig Filters uses the | character to apply filters to Twig variable followed by the filter name. Arguments can be passed in paranthesis similarly like Twig functions.Following table shows Twig Filters used in Grav:
Filters | Description | Example |
---|---|---|
Absolute URL | It takes the relative path and convert it to an absolute URL. |
'<img src="/some/path/img.jpg"/>' | absolute_urlconverts to: <img src = "http://learn.getgrav.org/some/path/img.jpg" /> |
Camelize | It converts a string to CamelCase format. |
'contact_us'| camelizeconverts to: ContactUs |
Contains | It looks for a string in another string and displays 1 if it finds the string. |
'This is some string' | contains('some')it outputs: 1
|
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. |
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 displays as: True
|
FieldName | It filters the field name by changing dot into array notation. |
'field.name'|fieldNamedisplays it as: field[name] |
Humanize | It is used to convert a string to human readable format. |
'some_text_to_read'|humanizeit displays as: Some text to read |
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 displays as: apple:2, orange:1, peach:3, |
Left Trim | It is used to remove white spaces at beginning of a string and removes the matching character given from left side of the string. |
'/strip/leading/slash/'|ltrim('/')is displayed as: strip/leading/slash/ |
Markdown | It is used to convert the string containing markdown into HTML using the markdown parser of Grav. |
'## some text with markdown'|markdownis displayed as:
|
MD5 | The md5 hash for the string can be created by using this filter. |
'something'|md5is displayed as: 437b930db84b8079c2dd804a71936b5f
|
Monthize | By using Monthize filter we can convert an integer number of days to number of months. |
'61'|monthizeit displays as: 2
|
Nice Time | By using Nice Time filter we can output a date in nice human readable time format. |
page.date|nicetime(false)is displayed as: 3 hrs ago |
Ordinalize | Ordinals ( like 1st,2nd, 3rd ) can be given to integers by using Ordinalize filter. |
'78'| ordinalizeis displayed as: 78th
|
Pluralize | A string can be converted to its plural English form by using Pluralize filter. |
'child'|pluralizeis displayed as: children
|
Randomize | This is filter 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 %}Is displayed as: one, two, three, eight, six, five, nine, seven, ten, four, |
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('/')is displayed as: /strip/leading/slash |
Singularize | A string can be converted to English singular version by using Singular filter. |
'vehicles'|singularizeis displayed as: vehicle
|
Safe Email | Safe Email filter is used to convert an email address into ASCII characters so that it makes harder for email spam. |
"someoneemailaddress@domain.com"|safe_emailit outputs: someoneemailaddress@domain.com |
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, |
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')It outputs: true
|
Translate | It is used to translate a string into current language. You can refer multi-language documentation for more detailed information. |
MY_LANGUAGE_KEY_STRING
it displays:'Some text in English'
|
Translate Admin | It translates a string into current language which is set in the user.yaml file. | |
Titleize | A string is converted into Title Case format by using Titleize. |
'welcome page'|titleizeis displayed as: Welcome Page |
UnderScoreize | A given string is converted to under_scored format by using UnderScoreize filter. |
'ContactUs'|underscorizeis converted to: contact_us
|
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)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)truncates to: one sentence
You 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)is displayed as: one s
|
Twig Functions
Twig Functions are directly called by passing the parameter. Following table lists the functions:Functions | Description | Example |
---|---|---|
Array | This function cast a value to array. |
array(value) |
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']) |
Dump | It accepts a valid twig variable and dumps it into the Grav debugger panel. However the debugger should be enabled to see messages tab values. |
dump(page.header) |
Debug | This works same as the dump() function. | |
Gist | This function creates Gist embed code based on Github Gist ID. | |
Random String Generation | This function will create a random string with specified number of characters. These strings can be used as unique id or key. |
generate_random_string(10) |
Repeat | This function will repeat the string for given amount of time. |
repeat('Grav ', 10) will repeat Grav 10 times. |
String | Generates a random string of specified character length. |
ta (23) |
Translate Array | It is a functions connected with |ta filter. | |
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') |
Translate | Using Translate filter, a string is translated as the |t filter. |
t('SITE_NAME')is translated to: Site Name |
No comments:
Post a Comment