Support multiple instances of the same token type in token replacement

Created on 18 February 2013, over 11 years ago
Updated 9 August 2024, 3 months ago

Problem/Motivation

Is not possible to use two tokens of same type when replacing tokens in a string. For example:

$string = 'Node [node1:title] points to [node2:title]';
$string = token_replace($string, array('node1' => $node1, 'node2' => $node2));

Proposed resolution

All modules that implements hook_tokens() expect their tokens (declared in hook_token_info()) to have a certain type name ('node', 'user', etc) so we can't change this behavior because all modules implementing this hook should be updated.

Instead, the approach is to add an 'alias' to the type, and internally strip this alias and call token_generate with the clean type name.

For example, the first example using this approach:

$string = 'Node [node{pointer}:title] points to [node{pointed}:title]';
$string = token_replace($string, array('node{pointer}' => $node1, 'node{pointed}' => $node2));

The modified code is token_replace() function. After getting all standard tokens a new loop is added to process the token alias. For each token type a new token_generate call is made, passing the stripped token (without the alias name chunk) and the filtered data array with the object related to this alias.

For the previous example two additional token_generate() calls are made:

  • first call: $type is 'node', $tokens is first token alias tokens stripped ('title' => '[node:title]'), and $data is the filtered data ('node' => $node1).
  • second call: $type is 'node', $tokens is first token alias tokens stripped ('title' => '[node:title]'), and $data is the filtered data ('node' => $node1).

Remaining tasks

Add tests to test functionality in deep to allow start a discussion on this approach. Having test coverage would work very well as examples and basis for such a discussion.

Add documentation for this feature.

User interface changes

No UI changes.

API changes

Added new token_alias_scan() function similar to token_scan but scans for token alias.

Additional notes

โœจ Feature request
Status

Needs work

Version

11.0 ๐Ÿ”ฅ

Component
Tokenย  โ†’

Last updated 3 days ago

No maintainer
Created by

๐Ÿ‡บ๐Ÿ‡ธUnited States dave reid Nebraska USA

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024