Custom field methods

Using field methods

Kirby 2 comes with a new way to work with fields in templates, by simply chaining helper methods.

Old way (still works)

<h1><?= html($page->title()) ?></h1>
<?= kirbytext($page->text()) ?>

New way

<h1><?= $page->title()->html() ?></h1>
<?= $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.

Available field methods

For a full list of available field methods, please check out the cheat sheet.

Getting started

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

The $field object gives you access to three important attributes.

- $field->key
The name of the field
- $field->value
The raw content of the field
- $field->page
The parent $page object

$field->value can be overwritten with a custom/modified value by your method.

Return options

There are three common scenarios, what field methods can do:

1. Modifying the field for further chaining

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.

Example

<?= $page->title()->quotes()->lower() ?>

2. Directly returning a modified value

field::$methods['quote'] = function($field) {
    return '“' . $field->value . '”';
};

When you directly return the modified value, further chaining is not possible.

Example

<?= $page->title()->quotes()->lower() ?>
<!-- will throw an error -->

<?= $page->title()->quotes() ?>
<!-- will work fine -->

3. Returning info about the field

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.

Example

<?php if($page->title()->hasQuotes()) ?>
The title is wrapped in quotes.
<?php endif ?>

Working with method arguments

In some cases it might be helpful to be able to pass arguments to the method:

<?= $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;
};