Learn how to build your own field methods
Kirby 2 comes with a new way to work with fields in templates, by simply chaining helper methods.
<h1><?php echo html($page->title()) ?></h1>
<?php echo kirbytext($page->text()) ?>
<h1><?php echo $page->title()->html() ?></h1>
<?php echo $page->text()->kirbytext() ?>
The new way keeps the templates cleaner and is more readable and easier to write. It's also more flexible and can be combined in great ways.
For a full list of available field methods, please check out the cheat sheet.
You can extend the set of defined field methods very easily. The best place to do this is in a plugin file: /site/plugins/methods.php
field::$methods['quote'] = function($field) {
return '“' . $field->value . '”';
};
This example shows the basic architecture of a field method. You define the method name with the key for the field::$methods
array. The callback function receives the $field
object as first argument.
The $field
object gives you access to three important attributes.
$field->value can be overwritten with a custom/modified value by your method.
There are three common scenarios, what field methods can do:
field::$methods['quote'] = function($field) {
$field->value = '“' . $field->value . '”';
return $field;
};
If you want to make it possible that the field value can be further modified by other field methods, you must modify the field value and return the field object.
<?php echo $page->title()->quotes()->lower() ?>
field::$methods['quote'] = function($field) {
return '“' . $field->value . '”';
};
When you directly return the modified value, further chaining is not possible.
<?php echo $page->title()->quotes()->lower() ?>
<!-- will throw an error -->
<?php echo $page->title()->quotes() ?>
<!-- will work fine -->
field::$methods['hasQuotes'] = function($field) {
return preg_match('^“.*”$', $field->value);
};
Field methods can also be used to make if clauses easier or return info about a value, such as the length or the readingtime.
<?php if($page->title()->hasQuotes()) ?>
The title is wrapped in quotes.
<?php endif ?>
In some cases it might be helpful to be able to pass arguments to the method:
<?php echo $page->title()->quote('«', '»') ?>
The definition for such a method with arguments is very simple:
field::$methods['quote'] = function($field, $start = '“', $end = '”') {
$field->value = $start . $field->value . $end;
return $field;
};