On this page
Filter API overview
Last updated on
25 August 2023
The Filter API is conceptually the same in Drupal 8 as it was in Drupal 7 and before. The major changes are:
- New filters can be defined using plugins instead of hooks.
- Filters now need to specify a filter type if they want to work well with in-place editing.
API features
- Text format config entities
\Drupal\filter\Entity\FilterFormat
config entity: configure text formats, one text format can have one text editor.- Every text format consists of an ordered list of filters (filter plugins), with settings for those filters that do have settings. When filtering text, these filters are invoked in order.
- Filter plugins
\Drupal\filter\Plugin\FilterInterface
: filter plugins, to provide additional filters that are available to site builders to be used.- Plugin implementations must be annotated with the
@Filter
annotation so they can be discovered. - Discovered plugins' annotation metadata can be altered using
hook_filter_info_alter()
\Drupal\filter\Plugin\FilterBase
provides a default implementation so filter plugins don't need to implement every method- Every filter plugin must specify a filter type in its annotation. Filter types were added specifically to support in-place editing. There are four filter types:
FilterInterface::TYPE_MARKUP_LANGUAGE
— Non-HTML markup language filters that generate HTML. The filter converts something that's not HTML to HTML in a way that is not compatible with WYSIWYG editing.FilterInterface::TYPE_HTML_RESTRICTOR
— HTML tag and attribute restricting filters to prevent XSS attacks. The filter restricts the HTML allowed, for example, to protect against XSS.FilterInterface::TYPE_TRANSFORM_REVERSIBLE
— Reversible transformation filters. The filter performs a transform for which a WYSIWYG plugin exists to perform the same transformation (and its reverse) client-side. For example,<img data-caption="Druplicon">
may be (reversibly!) transformed to<figure><img><figcaption>Druplicon</figcaption></figure>
.FilterInterface::TYPE_TRANSFORM_IRREVERSIBLE
— Irreversible transformation filters. The filter performs a transform for which a WYSIWYG plugin does not exist to perform the transformation client-side (especially, the reverse of it); instead, the WYSIWYG editor displays the unfiltered text. For example, Token Filter.
- Plugin implementations must be annotated with the
- check_markup()
- Using the check_markup() function, you can filter a user-supplied string using a text format. The return value has the type
MarkupInterface
and is fully filtered against the configured format.
See also
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion