decouple-1.0.x-dev/src/Plugin/Block/DecoupleBlock.php

src/Plugin/Block/DecoupleBlock.php
<?php

namespace Drupal\decouple\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Decouple Block' Block.
 *
 * @Block(
 *   id = "decouple_block",
 *   admin_label = @Translation("Decouple Block"),
 * )
 */
class DecoupleBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node && $node->bundle() == "decouple") {
      $root_element_id = $node->get('field_decouple_root_element_id')->value;
      $data_url = $node->get('field_decouple_data_url')->value ?? "";
      $js_file_path = $node->get('field_decouple_js_file_path')->value;
      $css_file_path = $node->get('field_decouple_css_file_path')->value ?? "";
    }

    $html = "<br />";
    $html .= "<div id=" . $root_element_id . " data-url=" . $data_url . ">" . PHP_EOL;
    $html .= "</div>" . PHP_EOL;

    return [
      '#markup' => $html,
      '#attached' => [
        'html_head_link' => [
          [
            [
              'rel' => 'stylesheet',
              'href' => "$css_file_path",
            ],
            TRUE,
          ],
        ],
        'html_head' => [
          [
            [
              '#tag' => 'script',
              '#attributes' => ['type' => 'text/javascript'],
              '#value' => 'document.addEventListener("DOMContentLoaded", function() {
                          var script = document.createElement("script");
                          script.src = "' . $js_file_path . '";
                          document.body.appendChild(script);
                        });',
            ],
            'custom_footer_js',
          ],
        ],
      ],
      '#allowed_tags' => ['div', 'h1', 'script', 'link'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    // Cache the block separately for each route.
    return ['route'];
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc