How to create custom token in Drupal 8

Step 1:
You need to create custom module for creating custom tokens.
Custom module need below file structure

your_module_name.info.yml
your_module_name.module
your_module_name.tokens.inc

Step 2

Create your_module_name.info.yml file
name: your_module_name
description: 'Tokens example'
type: module
core: 8.x

Step 3

Create your_module_name.module file
<?php
module_load_include('inc', 'your_module_name', your_module_name.tokens');

Step 4
Create your_module_name.tokens.inc file

Creating skelton for hooks
<?php
use DrupalCoreRenderBubbleableMetadata;
use SymfonyCmfComponentRoutingRouteObjectInterface;
use DrupalCoreUrl;
/**
* Implements hook_token_info().
*/
function your_module_name_token_info() {
}
/**
* Implements hook_tokens().
*/
function your_module_name_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
}

Filling hooks:
use DrupalCoreRenderBubbleableMetadata;
use SymfonyCmfComponentRoutingRouteObjectInterface;
use DrupalCoreUrl;
/**
* Implements hook_token_info().
*/
function your_module_name_token_info() {
$types['etf'] = array(
'name' => t("Site information"),
'description' => t("Tokens for etf-wide settings and other global information."),
);
// Site-wide global tokens.
$etf['title'] = array(
'name' => t("Title"),
'description' => t("The name of the etf."),
);
return array(
'types' => $types,
'tokens' => array(
'etf' => $etf,
),
);
}
/**
* Implements hook_tokens().
*/
function your_module_name_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$token_service = Drupal::token();
$request = Drupal::request();
$route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
$title = !empty(Drupal::service('title_resolver')->getTitle($request, $route)) ? Drupal::service('title_resolver')->getTitle($request, $route) : 'Home' ;
$replacements = array();
if ($type == 'etf') {
foreach ($tokens as $name => $original) {
switch ($name) {
case 'title':
$bubbleable_metadata->addCacheableDependency($title);
$replacements[$original] = $title;
break;
}
}
}
return $replacements;
}

Related Post


Latest Post


Recent Posts Widget

Make sure to never miss a thing...

Get the latest news from the creative industry along with other creative goodies, conveniently delivered to social media.