In Drupal 9, you can create custom tokens using the Token API for your custom module. The Token API provides a central API for modules to use to provide tokens. Tokens are placed into text by using the [type:token] syntax, where type is the machine-readable name of the token type, and token is the machine-readable name of the token within the type.
- Create a yourmodule.tokens.inc in your custom module directory.
- Define your custom token type:
/** * Implements hook_token_info(). */ function yourmodule_mailout_token_info() { $types['yourtype'] = [ 'name' => t('Your Type'), 'description' => t('Tokens for Your Module.'), ]; $tokens['yourtoken'] = [ 'name' => t("Your Token"), 'description' => t('The custom token'), ]; return [ 'types' => $types, 'tokens' => ['yourtype' => $tokens], ]; }
- Define the token replacements:
use Drupal\Core\Render\BubbleableMetadata; /** * Implements hook_tokens(). */ function yourmodule_mailout_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { $replacements = []; if($type == 'yourtype') { foreach ($tokens as $name => $original) { switch ($name) { case 'yourtoken': $replacements[$original] = 'Your replacement'; break; } } } return $replacements; }
- Use your custom token in your module or in any field or text area by adding [yourtype:yourtoken] to the text.
Add new comment