Token is an essential module available for both versions of drupal, There are lots of other modules that are dependent on the token module. it provides us global replacement patterns/tag, and so tokens provide us dynamic values. There is a list of global tokens available in token module and other popular modules also define their own tokens which help site builders to get dynamic values. Sometimes we may need to define our own token and replacement patterns.

I believe you all know the Drupal 8 module structure, so let's start with the important code. We are going to use two important hooks in our example

  • hook_token_info
  • hook_tokens
<?php
/**
 * Implements hook_token_info().
 */
function custom_token_info(){
    $types['custom_type'] = [
        'name' => t("My Custom Type"),
        'description' => t("Custom token type defined for sitewide used."),
    ];
    // Site-wide global token.
    $mytoken['custom_name'] = [
        'name' => t("Custom Token Name"),
        'description' => t("Defined the custom token name."),
    ];
    return [
        'types' => $types,
        'tokens' => [
            'custom_type' => $mytoken,
        ],
    ];
}
/**
 * Implements hook_tokens().
 */
function custom_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
    $replacements = [];
    if ($type == 'custom_type') {
        foreach ($tokens as $name => $original) {
            switch ($name) {
                case 'custom_name':
                    /**
                     * Write your code here
                     */
                    $config = \Drupal::config('system.site');
                    $bubbleable_metadata->addCacheableDependency($config);
                    $replacements[$original] = $config->get('name');
                    break;
            }
        }
    }
    return $replacements;
}