3

I'm attempting to use the token filter programmatically inside a .theme file like so.

function mytheme_preprocess_block(&$vars){
  $token = Drupal::token();
  $vars['label'] = $token->replace('[node:title]');
}

I looked at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21Token.php/function/Token%3A%3Areplace/8.2.x for information. However when I output $vars['label'] all it produces is [node:title] as if no replacement occurred at all. How would I programmatically initiate the token filter?

UPDATE: As a test I attempted using another method of token to make sure anything was happening at all by using $token->scan('[node:title]'); and it did spit out

array(1) { ["node"]=> array(1) { ["title"]=> string(12) "[node:title]" } }

So I know I invoked the token class properly at least

UPDATE: It appears that the token replace was working it just didn't recognize [node:title]. Using [site:name] did produce the expected result. How would I be able to get [node:title] to work? Do I need to supply it with that data?

3

Data about the node needed to be supplied as a parameter to the replace method. It worked once I used

$node = \Drupal::routeMatch()->getParameter('node');
$vars['label'] = $token->replace($vars['label'],['node' => $node]);

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.