How to create drupal 8 custom token module

,

Here is the steps for creating custom token 
First you need to create two files with name custom_token.info.yml & custom_token.module
change custom_token with your module name
Add the following code in your custom_token.info.yml file

name: Custom token
type: module
description: 'Allow users to define custom tokens to use thoughout the site' 
# core: '8.x'

# Information added by Drupal.org packaging script on 2016-07-11
version: '8.x-1.x-dev'
core: '8.x'
project: 'custom_token'
datestamp: 1468232040

and add the following code in your custom_token.module file

<?php
 
use DrupalCoreRenderBubbleableMetadata;  

function custom_token_token_info() {
  $info['tokens']['ctoken']['base_path'] = array(
    'name' => t('Base Path'),
    'description' => t("Base Path."),
  );
  return $info;
} 

function custom_token_tokens($type, $tokens, array $data = array(), array $options = array()) {
  $url_options = array('absolute' => TRUE);
  global $base_url;
  $sanitize = !empty($options['sanitize']);
  $replacements = array();
  if ($type == 'ctoken') {
    
    foreach ($tokens as $name => $original) {
      switch ($name) { 
    case 'base_path': 
          $replacements[$original] = $base_url;
          break; 
      }
    }
  
  }

  return $replacements;
}

 After created both files goto dashboard and enable the module. once enabled & made any changes please clear the browser cache
Usage
call the token like below code [ctoken:base_path] 
ctoken – token base 






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.