Listing available tokens
Last updated on
30 April 2025
To display a list of available tokens in your module or code, use the following examples.
Drupal 8
In a form:
$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.
);
Drupal 7
In a form:
$form['tokens'] = array(
'#theme' => 'token_tree_link',
// To get these options to work, use the patch from https://www.drupal.org/node/2289203 if you have Token 7.x-1.5 or earlier.
'#token_types' => array('node'), // The token types that have specific context. Can be multiple token types like 'term' and/or 'user'
'#global_types' => TRUE, // A boolean TRUE or FALSE whether to include 'global' context tokens like [current-user:*] or [site:*]. Defaults to TRUE.
'#click_insert' => TRUE, // A boolean whether to include the 'Click this token to insert in into the the focused textfield' JavaScript functionality. Defaults to TRUE.
);
In a render array:
$form['tokens'] = array(
'#theme' => 'token_tree',
'#token_types' => array('node'),
'#global_types' => FALSE,
'#click_insert' => FALSE,
);
Drupal 6
The parameters to theme('token_tree') are the following in order:
- The array of token types to display.
- A boolean to allow the global token types (defaults to TRUE).
- A boolean to allow the click-insert JavaScript functionality (defaults to TRUE).
In a form:
$form['tokens'] = array(
'#value' => theme('token_tree', array('node'), TRUE, TRUE),
);
In a page output:
$output = ...
$output .= '<h4>Available tokens:</h4>';
$output .= theme('token_tree', array('node'), TRUE, TRUE);
return $output;
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion