<?php /** * Implements hook_token_info(). */ function mycustomtokenmodule_token_info() { $type = [ 'name' => t('Custom Token'), 'description' => t('Tokens for custom things.'), ]; $node['title'] = [ 'name' => t("Node Title"), 'description' => t('The node\'s title'), ]; $node['dateformat'] = [ 'name' => t("Custom Date Format"), 'dynamic' => TRUE, 'description' => t('Show a custom format for the current date'), ]; return [ 'types' => ['customtoken' => $type], 'tokens' => ['customtoken' => $node], ]; } /** * Implements hook_tokens(). */ function mycustomtokenmodule_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) { $replacements = []; if ($type == 'customtoken' && !empty($data['node'])) { foreach ($tokens as $name => $original) { switch ($name) { case 'title': $replacements[$original] = $data['node']->getTitle(); break; } } if ($dateTokens = \Drupal::token()->findWithPrefix($tokens, 'dateformat')) { // var_dump($dateTokens) // retult: array(1) { ["Y-m-d"]=> string(30) "[customtoken:dateformat:Y-m-d]" } foreach ($dateTokens as $format => $original) { $replacements[$original] = date($format); } } } return $replacements; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter