Tokens in Drupal: how they work and what they can give your website

Tokens in Drupal: how they work and what they can give your website

26 أغسطس 2022

Our every morning starts with coffee. This day will be no exception. Pour yourself a hot espresso or teacup, and let's explore tokens in Drupal with us. What is a Drupal token, how do they work, and what can they give your website?
If you need help activating your Drupal token, please refer to the Drupal 8 services page. Honestly, it's not that easy to do if you're not a developer. Try to do it yourself, but if you need help, you have someone you can turn to!

What is a Drupal token?

First, we would like to point out that we are not talking about those digital currency tokens but rather Drupal tokens.
According to TechTerms definition:
"Token is a single element of a programming language. There are five categories of tokens: 1) constants, 2) identifiers, 3) operators, 4) separators, and 5) reserved words." We want to add to that meaning something else. The token is a variable in Drupal. They are a set of 'placeholder' that help you automatically fill in the dynamic data and complete tasks. Tokens are the usual line and can stand alone or be inside another line and include as many tokens as you want.
Tokens have the following top three characteristics:

  • Tokens cannot be paired
  • Tokens separate their sequence with a colon:
  • Tokens should have two or more parts

For example, tokens might look like this:
Hi [current-user:name], Welcome to the page [node:title].

Let's imagine that your name is Mikayla, and you enter the Golems web development company site. As a result, you will see the following:
Hi Mikayla, Welcome to the Golems page.

The token itself appears after the colon (:). In other words, you are specifying what value will be substituted into the string containing the token. :name here indicates that we want to know the current user's username. A token is used to dynamically generate a welcome line for each site user instead of a hard-coding one. According to this example, the tokens must know the current user and which node the user is currently viewing.

What are tokens used for?

Tokens can have a wide variety of attributes. Depending on the context, they are used when some kind of dynamic is needed. Therefore, tokens are variable. Typically, these variables are used in Drupal to generate URL aliases (pathauto), meta tags (metatag), and various messages for email newsletters. Tokens are used wherever dynamics are needed. Their scope and sphere of application are very broad.
There are 3 main groups of tokens:

  • Built-in tokens

They are used for global site variables—for example, the site name.

  • Contextual tokens

They are used depending on the context—for example, the login name of the current user.

  • Utility tokens

For example, a random number.

What tokens are available in Drupal 8?

There are many tokens available in Drupal. But to start working with them and experience all the benefits of tokens, you need to install the Drupal token module. The Token module is optional, but it can help you a lot with tokens. After installation, click Help - Token page (/admin/help/token). There you can see all available tokens.

The Drupal token module gives you the following benefits:

  • It adds more useful tokens. For example, you can get tokens for existing node fields.
  • It makes working with tokens easier for developers.
  • It provides a convenient user interface to browse and select tokens appropriate for the current context.

9 most common Drupal 8 tokens

  1. [node:title]- title field. The title of the node.
  2. [node:body]- body. The body text of the node.
  3. [node:changed]- date changed. The most recent node update date.
  4. [node:created]- date created. The date the node was created.
  5. [node:url]- URL. The URL of the node.
  6. [comment:author:mail]- Email. The email address of the user.
  7. [current-page:title]- title. The title of the current page.
  8. [node:author]- author. The name of the author of the node.
  9. [node:language]- language. The language in which the node is written.

More information is available in the Token Documentation (drupal.org). The list of tokens will differ from website to website. This depends entirely on the modules you have installed or plan to install. Other factors include the content types and other content entities you will configure, the version of the Drupal site, and many others. There are, however, a few base tokens that can be found on most sites, including Drupal 8 tokens. The following code example demonstrates finding a list of available tokens in the module or code. 

$form['tokens'] = \Drupal::service('token.tree_builder')->buildRenderable(['node', 'user']); // Pass your entity machine name as parameter in an array to add it to the list. );

How to create a custom token in Drupal 8?

We have now reached the most crucial question for those interested in the topic. How can you create your own token?
There are two hooks for creating custom tokens:

  1. hook_token_info():

It collects all information about tokens and their types.
Example:

/**
* Implements hook_token_info().
*/
function hook_token_info(){
$type = [
'name' => t('Nodes'),
'description' => t('Tokens related to individual nodes.'),
'needs-data' => 'node',
];
 
// Core tokens for nodes.
$node['nid'] = [
'name' => t("Node ID"),
'description' => t("The unique ID of the node."),
];
 
// Chained tokens for nodes.
// This token return token of type `user` and will look
// for tokens for group user. And e.g. node:author will have
// tokens from user group, such as node:author:name where is
// name - token for group user.
 
$node['author'] = [
'name' => t("Author"),
'type' => 'user',
];
 
return [
'types' => ['node' => $type],
'tokens' => ['node' => $node],
];
}
  1. hook_tokens():

It replaces tokens with values. This hook should restore an array with token replacements. If there were no replacements, then they should restore an empty array.
Example:

/** 
* Implements hook_tokens(). 
*/
function hook_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
 
$token_service = \Drupal::token(); 
$replacements = []; 
 
if ($type == 'node' && !empty($data['node'])) { 
/** @var \Drupal\node\NodeInterface 
$node */ $node = $data['node']; 
 
foreach ($tokens as $name => $original) { 
switch ($name) { 
 
// Simple key values on the node. 
case 'nid': 
$replacements[$original] = $node->nid; 
break; 
 
// Default values for the chained tokens handled below. 
case 'author': 
$account = $node->getOwner() ? $node->;getOwner(): User::load(0); 
$replacements[$original] = $account->label(); 
$bubbleable_metadata->;addCacheableDependency($account); 
break;
}
}
 
if ($author_tokens = $token_service->;findWithPrefix($tokens, 'author'){ 
$replacements += $token_service->generate('user', $author_tokens,
['user' =>; $node->getOwner()], $options, $bubbleable_metadata);  
}
} 
 
return $replacements; 
}

* There are two alter hooks: hook_token_info_alter() and hook_tokens_alter(). With these hooks, you can customize the behavior of the already existing tokens.

Then you check if the type of token you need has arrived, if it has all the necessary data and if they are in place. If all is well, you should just loop through and replace the tokens with their values.

Extend your website with Drupal tokens!

Only those who do not know how to use Drupal tokens speak badly about them. There are many of them, and they greatly simplify life and save money for the owners of Drupal sites. Use the Drupal module development service to learn more about tokens and help create or customize them.

Comments

An
مجهول