token_entity_render-8.x-1.x-dev/token_entity_render.module
token_entity_render.module
<?php /** * @file * Hook implementations for token_entity_render. */ use Drupal\Core\Render\BubbleableMetadata; /** * Implements hook_token_info_alter(). */ function token_entity_render_token_info_alter(array &$data) { // Load all possible view modes. $all_view_modes = \Drupal::service('entity.manager')->getStorage('entity_view_mode')->loadMultiple(); // Traverse all view modes. foreach ($all_view_modes as $mode) { // Leave if no entity type is set. if (!isset($data['tokens'][$mode->getTargetType()])) { continue; } // Load the entity type definition. $entity_type_definition = \Drupal::service('entity_type.manager')->getDefinition($mode->getTargetType()); // Remove the prefix from the view mode name. $mode_name = preg_replace('/(.*?\.)/', '', $mode->id()); // Add token information. $data['tokens'][$mode->getTargetType()]['render:' . $mode_name] = [ 'name' => $mode->label(), 'description' => t('Muestra la entidad @entity_type usando el modo de visualización @view_mode.', [ '@entity_type' => $entity_type_definition->getLabel(), '@view_mode' => $mode->label(), ]), ]; } } /** * Implements hook_tokens(). */ function token_entity_render_tokens($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) { $replacements = []; $to_process = []; if (!isset($data['entity_type'])) { // Don't do anything if not processing an entity. return $replacements; } // We have to discard quickly those tokens we are not to process. foreach ($tokens as $token_key => $token_replaceable_value) { $token_prefix = 'render:'; if (strpos($token_key, $token_prefix) === FALSE) { // This is faster than regexp or strstr. continue; } $to_process[$token_replaceable_value] = substr($token_key, strlen($token_prefix)); } if (!$to_process) { // Don't do anything if nothing to process. return $replacements; } // Load all possible view modes. $all_view_modes = \Drupal::service('entity.manager')->getStorage('entity_view_mode')->loadMultiple(); // Traverse again all tokens to process. $renderer = \Drupal::service('renderer'); foreach ($to_process as $token_replaceable_value => $view_mode_name) { // If the view mode actually exists and if the entity type matches. if (($view_mode = $all_view_modes[$data['entity_type'] . '.' . $view_mode_name])) { // The view mode name does not have the entity name. $mode_machine_name = substr($view_mode->id(), strlen($view_mode->getTargetType()) + 1); $rendered_entity = \Drupal::entityTypeManager()->getViewBuilder($view_mode->getTargetType())->view($data['entity'], $mode_machine_name); // Add the replacement. $replacements[$token_replaceable_value] = $renderer->renderPlain($rendered_entity); } } // Return replacements, if any. return $replacements; }