You are here

function addtoany_page_attachments in AddToAny Share Buttons 8

Implements hook_page_attachments().

File

./addtoany.module, line 120
Handle AddToAny integration.

Code

function addtoany_page_attachments(&$page) {
  $config = \Drupal::config('addtoany.settings');

  // Initial JavaScript.
  $additional_js = $config
    ->get('additional_js');
  if (\Drupal::moduleHandler()
    ->moduleExists('token')) {
    $node = \Drupal::routeMatch()
      ->getParameter('node');
    $data = [];
    if ($node) {
      if (is_numeric($node)) {
        $node = Node::load($node);
      }
      $data = [
        'node' => $node,
      ];
      $additional_js = \Drupal::token()
        ->replace($additional_js, $data);
    }
  }
  $javascript_header = 'window.a2a_config=window.a2a_config||{};' . 'a2a_config.callbacks=[];a2a_config.overlays=[];' . 'a2a_config.templates={};' . $additional_js;

  // Add AddToAny initial JS config.
  $page['#attached']['html_head'][] = [
    // The data.
    [
      // Add a <script> tag.
      '#tag' => 'script',
      // Add JavaScript to the <script> tag.
      '#value' => Markup::create($javascript_header),
      // Give weight so it appears after meta tags, etc.
      '#weight' => 10,
    ],
    // Assign a key to reference this HTML <HEAD> element when altering.
    'addtoany-js',
  ];

  // Custom CSS.
  $css = $config
    ->get('additional_css');
  if (!empty($css)) {

    // Add AddToAny custom CSS.
    $page['#attached']['html_head'][] = [
      // The data.
      [
        // Add a <style> tag.
        '#tag' => 'style',
        // Add CSS to the <style> tag.
        '#value' => $css,
        // Give weight so it appears after meta tags, etc.
        '#weight' => 10,
      ],
      // Assign a key to reference this HTML <HEAD> element when altering.
      'addtoany-css',
    ];
  }

  // Add module's main library, which includes external AddToAny core JS,
  // and the module's CSS.
  // Enable the libraries if the current route is not an admin page.
  $route = \Drupal::routeMatch()
    ->getRouteObject();
  if (!\Drupal::service('router.admin_context')
    ->isAdminRoute($route)) {
    $page['#attached']['library'][] = 'addtoany/addtoany';
  }
}