How to create drupal 8 custom token module for theme path ?

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

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

# Information added by 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

use DrupalCoreRenderBubbleableMetadata;  

function custom_token_token_info() {
  $info['tokens']['ctoken']['base_path'] = array(
    'name' => t('Base Path'),
    'description' => t("Base Path."),
  $info['tokens']['ctoken']['theme_path'] = array(
    'name' => t('Theme Path'),
    'description' => t("Theme 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;
   case 'theme_path': 
    $replacements[$original] = $base_url.'/'.Drupal::theme()->getActiveTheme()->getPath(); 

  return $replacements;

After created both files goto dashboard and enable the module. once enabled & made any changes please clear the browser cache
call the token like below code [ctoken:base_path]
call the token like below code [ctoken:the_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.