I have created a token in .module
file. that gives current node title.
But every-time I change the title of node, I have to rebuilt cache so that updated title get reflected in my token.
Of-course clearing cache again and again on every page refresh is not a good idea.
Any other way to call hook_token_info
and hook_tokens
automatically on every page load?
PS: I also installed "token" module and this module is using hook_module_implements_alter(&$implementations, $hook)
.
@edit:
function hook_token_info() {
$info = array();
$info['tokens']['etf']['node-title'] = array(
'name' => t('Node Title'),
'description' => t("Provides current node title."),
'type' => 'etf',
);
return $info;
}
function hook_tokens($type, array $tokens, array $data = array(), array $options = array(), BubbleableMetadata $bubbleable_metadata) {
$replacements = array();
$url_options = array('absolute' => TRUE);
if(isset($options['langcode'])) {
$url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
$langcode = $options['langcode'];
}
else {
$langcode = NULL;
}
$request = \Drupal::request();
$route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT);
$title = \Drupal::service('title_resolver')->getTitle($request, $route);
if ($type == 'etf') {
foreach ($tokens as $name => $original) {
switch ($name) {
case 'node-title':
$replacements[$original] = $title;
// drupal_flush_all_caches();
// sleep(2);
break;
}
}
}
return $replacements;
}
All code is written in .module file
hook_module_implements_alter()
matters for the answer.