bodyタグにnode idやaliasのClassを追加する方法

カテゴリ テーマ コアバージョン 8.4x 関連モジュール hook_preprocess_html
/**
 * Implements hook_preprocess_HOOK() for html.html.twig.
 */
function your_theme_preprocess_html(array &$variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $alias = explode('?', $_SERVER['REQUEST_URI']);
  $alias = $alias[0];

  // Node type.
  if (preg_match('!^/node/([0-9]+)!', $current_path, $m)) {
    $variables['attributes']->addClass("node--$m[1]");
  }

  // Alias.
  if ($alias) {
    $aliases = explode('/', $alias);
    array_shift($aliases);
    $suggestion = [];
    foreach ($aliases as $a) {
      $suggestion[] = $a;
      $variables['attributes']->addClass(implode('--', $suggestion));
    }
  }
}

OTHER FAQ