Drupal 8 View Mode custom Rout with out using views

So you want to use a new node display mode "view mode" but dont want to use a view...
thats cool here is how.

1) go to site.com/admin/structure/display-modes/view
add a new view mode ill name it "test" which gives me '

node.test'

2) go to your content types "mannage display" scrole to the bottom and select your new view mode

3 ) in a new module my_module.routing.yml file
add

my_module.node.test:
 path: '/something/{node}/something'
 defaults:
   _entity_view: node.test
 requirements:
   _permission: 'access content'

then drush cr (clear cache )
and goto site.com/something/NODE_ID/something
if you really want to start messing with it  you can then add to my_module.module file

/**
 * Implements hook_ENTITY_TYPE_view().
 */
function my_module_node_view(array &$build, EntityInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if (!empty($node) && is_object($node)) {
    $type = $node->getType();
    if ($type == 'some_content_type') {
      if ($view_mode == 'test') {
        // could use your own service return \Drupal::service('my_module.node.view')->hookNodeView($build, $node, $display, $view_mode);
        $labels = [];
        $field_groups = $build['#fieldgroups'];
        unset($build['#fieldgroups']);
        foreach ($field_groups as $key => $field) {
          $labels[$key] = $field->label;
        }
         $build['extra'] = [
          '#theme' => 'some_theme',
          '#context' =>  $field_groups,
         ];
      }
    }
  }
}

/**
 * Implements hook_theme().
 */
function my_module_theme($existing, $type, $theme, $path) {
  return [
    'some_theme' => [
      'variables' => [
        'context' => [],
      ],
      'template' => 'my-twig-template',
    ],


then {{dump(context)}}
this just gives you the idea

 

Category: