Twig functions are called directly with any parameters being passed in via parenthesis.
arrayCast a value to array
[prism classes="language-twig line-numbers"] {% set value = array(value) %} [/prism]
array_diffComputes the difference of arrays.
[prism classes="language-twig line-numbers"] {% set diff = array_diff(array1, array2...) %} [/prism]
array_key_valueThe array_key_value function allows you to add a key/value pair to an associate array
[prism classes="language-twig line-numbers"] {% set my_array = {fruit: 'apple'} %} {% set my_array = array_key_value('meat','steak', my_array) %} {{ print_r(my_array)}} [/prism]
outputs: Array ( [fruit] => apple [meat] => steak )
array_key_existsWrapper for PHP's array_key_exists function that returns whether or not a key exists in an associative array.
[prism classes="language-twig line-numbers"] {% set my_array = {fruit: 'apple', meat: 'steak'} %} {{ array_key_exists('meat', my_array) }} [/prism]
outputs: 1
array_intersectThe array_intersect function provides the intersection of two arrays or Grav collections.
[prism classes="language-twig line-numbers"] {% set array_1 = {fruit: 'apple', meat: 'steak'} %} {% set array_2 = {fish: 'tuna', meat: 'steak'} %} {{ print_r(array_intersect(array_1, array_2)) }} [/prism]
outputs: Array ( [meat] => steak )
array_uniqueWrapper for PHP array_unique() that removes duplicates from an array.
array_unique(['foo', 'bar', 'foo', 'baz']) Array
(
[0] => foo
[1] => bar
[3] => baz
)
authorizeAuthorizes an authenticated user to see a resource. Accepts a single permission string or an array of permission strings.
authorize(['admin.statistics', 'admin.super'])
[version=16,17]
body_classTakes an array of classes, and if they are not set on body_classes look to see if they are set in current theme configuration.
set body_classes = body_class(['header-fixed', 'header-animated', 'header-dark', 'header-transparent', 'sticky-footer'])
cronCreate a "Cron" object from cron syntax
cron("3 * * * *").getNextRunDate()|date(config.date_format.default)
[/version]
dumpTakes 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)
debugSame as dump()
evaluateThe evaluate function can be used to evaluate a string as Twig:
evaluate('grav.language.getLanguage')
evaluate_twigSimilar to evaluate, but will evaluate and process with Twig
evaluate_twig('This is a twig variable: {{ foo }}', {foo: 'bar'})) This is a twig variable: bar
exifOutput the EXIF data from an image based on its filepath. This requires that media: auto_metadata_exif: true is set in system.yaml. For example, in a Twig-template:
[prism classes="language-twig line-numbers"] {% set image = page.media['sample-image.jpg'] %} {% set exif = exif(image.filepath, true) %} {{ exif.MaxApertureValue }} [/prism]
This would write the MaxApertureValue-value set in the camera, for example "40/10". You can always use {{ dump(exif)}}ÿÿt„ to show all the available data in the debugger.
get_cookieRetrieve the value of a cookie with this function:
get_cookie('your_cookie_key')
[version=16,17]
get_typeGets the type of a variable:
get_type(page) object
[/version]
gistTakes a Github Gist ID and creates appropriate Gist embed code
gist('bc448ff158df4bc56217') <script src="https://gist.github.com/bc448ff158df4bc56217.js"></script>
header_varHelper function. Returns page.header.<variable>.
Given frontmatter of
---
title: Home
---
header_var('title') Home
[version=16,17]
http_response_codeIf response_code is provided, then the previous status code will be returned. If response_code is not provided, then the current status code will be returned. Both of these values will default to a 200 status code if used in a web server environment.
http_response_code(404)
[/version]
isajaxrequestthe isajaxrequest() function can be used to check if HTTP_X_REQUESTED_WITH header option is set:
json_decodeYou can decode JSON by simply applying this filter:
json_decode({"first_name": "Guido", "last_name":"Rossum"})
media_directoryReturns a media object for an arbitrary directory. Once obtained you can manipulate images in a similar fashion to pages.
media_directory('theme://images')['some-image.jpg'].cropResize(200,200).html
[version=16,17]
nicefilesizeOutput a file size in a human readable nice size format
nicefilesize(612394) 598.04 KB
nicenumberOutput a number in a human readable nice number format
nicenumber(12430) 12.43 k
nicetimeOutput a date in a human readable nice time format
nicetime(page.date) 8 months ago
[/version]
nonce_fieldGenerate a Grav security nonce field for a form with a required action:
nonce_field('action') <input type="hidden" name="nonce" value="1571cdd32756b2f6529f6010c742719f" />
[version=16,17]
of_typeChecks the type of a variable to the param:
of_type(page, 'string') false
[/version]
pathinfoParses a path into an array.
[prism classes="language-twig"] {% set parts = pathinfo('/www/htdocs/inc/lib.inc.php') %} {{ print_r(parts) }} [/prism]
outputs: Array ( [dirname] => /www/htdocs/inc [basename] => lib.inc.php [extension] => php [filename] => lib.inc )
[version=16,17]
print_rPrints a variable in a readable format
print_r(page.header)
[prism classes="language-text"] stdClass Object ( [title] => Twig Functions [body_classes] => twig__headers [page-toc] => Array ( [active] => 1 [start] => 3 [depth] => 1 ) [process] => Array ( [twig] => 1 ) [taxonomy] => Array ( [category] => docs ) ) [/prism]
[/version]
random_stringWill generate a random string of the required number of characters. Particularly useful in creating a unique id or key.
random_string(10) M4V7G0t5om
unique_idGenerates a random string with configurable length, prefix and suffix. Unlike the built-in PHP uniqid() function and the random_string utils, this string will be generated truly unique and non-conflicting.
unique_id(9) 9424445cf
unique_id(11, { prefix: 'user_' }) uniqueid(11, { prefix: 'user' }) }}
unique_id(13, { suffix: '.json' }) unique_id(13, { suffix: '.json' }) }}
rangeGenerates an array containing a range of elements, optionally stepped
range(25, 300, 50) Array
(
[0] => 25
[1] => 75
[2] => 125
[3] => 175
[4] => 225
[5] => 275
)
[version=16,17]
read_fileSimple function to read a file based on a filepath and output it.
read_file('plugins://admin/README.md')|markdown
[prism classes="language-markdown line-numbers"]
This admin plugin for Grav is an HTML user interface that provides a convenient way to configure Grav and easily create and modify pages... [/prism]
[/version]
redirect_meRedirects to a URL of your choosing
redirect_me('http://google.com', 304)
[version=16,17]
regex_filterPerforms a preg_grep on an array with a regex pattern
regex_filter(['pasta', 'fish', 'steak', 'potatoes'], "/p.*/")
[prism classes="language-text"] Array ( [0] => pasta [3] => potatoes ) [/prism]
regex_replaceA helpful wrapper for the PHP preg_replace() method, you can perform complex Regex replacements on text via this filter:
regex_replace('The quick brown fox jumps over the lazy dog.', ['/quick/','/brown/','/fox/','/dog/'], ['slow','black','bear','turtle'])
[prism classes="language-text"] The slow black bear jumps over the lazy turtle. [/prism]
[/version]
[version=17]
regex_matchA helpful wrapper for the PHP preg_match() method, you can perform complex regular expression match on text via this filter:
regex_match('http://www.php.net/index.html', '@^(?:http://)?([^/]+)@i')
[prism classes="language-text"] Array ( [0] => http://www.php.net [1] => www.php.net ) [/prism]
regex_splitA helpful wrapper for the PHP preg_split() method. Split string by a regular expression on text via this filter:
regex_split('hypertext language, programming', '/\\s*,\\s*/u')
[prism classes="language-text"] Array ( [0] => hypertext language [1] => programming ) [/prism]
[/version]
repeatWill repeat whatever is passed in a certain amount of times.
repeat('blah ', 10) blah blah blah blah blah blah blah blah blah blah
stringReturns a string from a value. If the value is array, return it json encoded
string(23) => "23"
string(['test' => 'x']) => {"test":"x"}
[version=17]
svg_imageReturns the content of an SVG image and adds extra classes as needed. Provides the benefits of inline svg without having to paste the code directly on the page. Useful for reusable images such as social media icons.
{{ svg_image(path, classes, strip_style) }}
strip_style = remove the svg inline styling - useful for styling with css classes.
example:
{{ svg_image('theme://images/something.svg', 'my-class-here mb-10', true) }}
[/version]
[version=16,17]
theme_varGet a theme variable from the page header if it exists, else use the theme config:
theme_var('grid-size')
This will first try page.header.grid-size, if that is not set, it will try theme.grid-size from the theme configuration file. it can optionally take a default:
theme_var('grid-size', 1024)
[/version]
tTranslate a string, as the |t filter.
t('SITE_NAME') Site Name
taFunctions the same way the |ta filter does.
tlTranslates a string in a specific language. For more details check out the multi-language documentation.
tl('SIMPLE_TEXT', ['fr'])
urlWill 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/sites/help.ambrosia.menu/themes/learn2/images/logo.png
vardumpThe vardump() function outputs the current variable to the screen (rather than in the debugger as with dump())
[prism classes="language-twig line-numbers"] {% set my_array = {foo: 'bar', baz: 'qux'} %} {{ vardump(my_array) }} [/prism]
[prism classes="language-twig"] [ "foo" => "bar" "baz" => "qux" ] [/prism]
[version=16,17]
xssAllow a manual check of a string for XSS vulnerabilities
xss('this string contains a <script>alert("hello");</script> XSS vulnerability') dangerous_tags
[/version]