Automad already provides a set of filters to modify the value of a variable. However, in some cases it may be necessary to use a custom function to process the content of a variable. Custom filters are written in plain PHP and their setup is very similar to the structure of a generic extension.
@{ variable | Vendor/Filter }
Package Structure
Like themes and generic extensions, custom filters are added to an Automad installation in form of a package. Also here, there are two types of packages: local packages and Composer packages.
Local Packages
The most simple structure of a custom filter package is a directory for your namespace inside the packages directory, containing a directory for your filter that shares the same name as the PHP file inside. Note that all file and directory names must be lowercase.
packages/
vendor/
filter/
filter.php
According to the directory structure above, the PHP file of the filter looks like this:
<?php
// The namespace corresponds to the directory structure.
namespace Vendor;
// Prevent direct access.
defined('AUTOMAD') or die('Direct access not permitted!');
// The class name corresponds to the filter directory and file name.
class Filter {
// The main method must have the same name as the class.
public function Filter(string $value): string {
// Modify the value here.
return $value;
}
}
Now the custom filter can be used in templates as follows:
@{ variable | Vendor/Filter }
Composer Packages
In Composer packages, classes are loaded by the autoloader of Composer, which allows for a more flexible file structure. The only important convention is that the main method has the same name as the class. Custom filters that are loaded by Composer are called in templates by the combination of their namespace and their class name. Add a composer.json file with the following content to the root of your package:
{
"name": "vendor/filter",
"description": "The filter description ...",
"type": "automad-package",
"keywords": ["extension"],
"license": "MIT",
"require": {
"automad/package-installer": "^1.1"
},
"autoload": {
"classmap": [""]
}
}
Find more information about publishing packages on the packages page.
Parameters
When a custom filter is called, the value of the variable is always passed as the first argument. Additional parameters can be passed in parentheses in the template:
@{ variable | Vendor/Filter ('first', 'second') }
Those parameters are simply appended to the list of arguments of the main method after the value of the variable:
<?php
namespace Vendor;
defined('AUTOMAD') or die('Direct access not permitted!');
class Filter {
public function Filter(string $value, string $prefix = '', string $suffix = ''): string {
return $prefix . $value . $suffix;
}
}
Return Values
The modified value has to be returned using a return statement. The returned value is then either passed to the next filter in the chain or rendered as the output of the variable statement.
@{ title | Vendor/Filter ('[', ']') | strtoupper }