What are tokens?
What are tokens?
Tokens are specially formatted chunks of text that serve as placeholders for a dynamically generated value. Here's a really simple example: You want to display a welcome message to user's of your site, and you want it to be personalized so you add their name and instead of just saying "Welcome", you want to say "Welcome, Joe". In order to avoid having to hard-code a welcome string for every single user of the site it would be nice to dynamically generate the string. So you use one like the following, "Welcome,
Anonymous" (where the token for
Anonymous looks like
Anonymous here is what Drupal refers to as a token. A string of static text that will be located and replaced with a dynamic value. This token is made up of a few parts, inside of the mandatory square brackets that signify that this is a token.
The first part
current-user: in this case is the token type. Token types are used to group similar things together into a namespace. Users, for example, have name, mail, and last-login properties. Nodes have title, nid (Node ID), and author properties. Token type also plays an important role in determining which tokens are available in what context. User tokens, for example, might be available when sending a confirmation email but node type tokens might be irrelevant in this use case. Webmasters should know what types of tokens can be used in what context so that they don't use a node token (which has no value) in a user context.
The second part, after the colon (
:) is the token itself. This signifies what value will be substituted into the string containing the token.
:name in this case indicates that we want the current user's username. This also brings up another important point: global vs. contextual tokens. Some tokens like this one
[system:date] can be calculated without any additional information. This token will simply call the PHP date function and you've got a value. This token
Anonymous, on the other hand, requires knowledge about the currently logged-in user in order to be able to determine that user's name. This token requires additional context in order to be useful.
To review, the (minimum) mandatory building blocks of a token are the:
- token type at the start
- token itself, (to represent a dynamically generated value)
- square brackets to contain it all
This information was copied from Drupalize.Me