You are here

function gatsby_node_view in Gatsby Live Preview & Incremental Builds 8

Same name and namespace in other branches
  1. 2.0.x gatsby.module \gatsby_node_view()

Implements hook_node_view().

File

./gatsby.module, line 208
Contains gatsby.module.

Code

function gatsby_node_view(array &$build, $entity, $display, $view_mode) {

  // Don't run hook_node_view if gatsby_endpoints is enabled.
  $moduleHandler = \Drupal::service('module_handler');
  if ($moduleHandler
    ->moduleExists('gatsby_endpoints')) {
    return;
  }
  $server_urls = array_map('trim', explode(',', \Drupal::config('gatsby.settings')
    ->get('server_url')));
  $server_url = reset($server_urls);

  // Override node view page with iframe to Gatsby site.
  if (!empty($build['#node']) && $view_mode == 'full') {
    $node = $build['#node'];

    // Load settings.
    $entity_type = NodeType::load($entity
      ->bundle());
    $iframe_settings = $entity_type
      ->getThirdPartySetting('gatsby', 'iframe');

    // We are wanting to render preview for this content type.
    if (!empty($iframe_settings)) {
      $gatsby_url = preg_replace('/\\/$/', '', $server_url) . \Drupal::service('gatsby.path_mapping')
        ->getPath($node);
      $build = [];
      $build['#node'] = $node;
      $build['#entity_type'] = 'node';

      // Render an iframe to the preview URL.
      $build['gatsby_preview'] = [
        '#type' => 'inline_template',
        '#template' => '<div class="gatsby-iframe-container"><iframe class="gatsby-iframe" src="{{ url }}"></iframe></div>',
        '#context' => [
          'url' => $gatsby_url,
        ],
        '#attached' => [
          'library' => [
            'gatsby/iframe_preview',
          ],
        ],
      ];
    }
  }
}