Tokens is a fundamental element in any Drupal site. It comprises of custom pieces of text that can be used as placeholders for predefined values. These tokens are placed in a [token:type] format.
In this article, I'll show you how to create custom image token in drupal 8 & 9.
Follow the instructions below to create our custom "custom_image_token" module:
Create custom_image_token.info.yml file:
Create custom_image_token.module file:
The first thing we’ll need in this file is, hook_tokens_info()
This is where we’ll define our token for Drupal. Which will make our new token available in UI.
In the second part of the code, the hook_tokens()
function is used to actually make the token perform its desired function.
Clear your Drupal caches, and then our new token will be available in UI like this.
Next steps
- Clear your Drupal caches. To do this I use this Drush command:
drush cr
if you don’t currently use Drush, I highly recommend using it, or the Drupal Console. - Now, go back to your site, and you should be able to see the new custom token.
- I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.
- This code can be found and downloaded from https://github.com/codimth/custom_image_token.