1

I'm attempting to add a custom token so I can use it in a view block. Looking at examples I've added this code to my custom .theme file

function mytheme_token_info(){
  $types['mytheme_tokens'] = [
    'name' => t('mytheme Tokens'),
    'description' => t('mytheme token type'),
  ];
  $currentnode_token['current_node_title'] = [
    'name' => t('Current Node Title'),
    'description' => t('Title of the current node'),
  ];
  return [
    'types' => $types,
    'tokens' => [
      'mytheme_tokens' => $currentnode_token,
    ],
  ];
}
function mytheme_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata){
  $token_service = \Drupal::token();
  $replacements = array();
  if($type == 'mytheme_tokens') {
    foreach($tokens as $name => $original){
      switch($name){
        case 'current_node_title':
        $node = \Drupal::routeMatch()->getParameter('node');
        $title = (!empty($node)) ? $node->title->value : ''; 
        $replacements[$original] = $title;
        break;
      }
    }
  }
  return $replacements;
}

But in my view in a custom text block I have a header using that token but it spits out

[mytheme_tokens:current_node_title] Products

And the token isn't replaced. I know for sure the tokenizer is running though because [site:title] did work.

How do you create custom globally available tokens?

| improve this question | | | | |
1

Themes can only implement alter, theme and pre/process hooks.

Re-implement those hooks in a custom module and they should work fine.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.