如何以编程方式获取Drupal 8中的内容类型名称

Rah*_*eth 7 content-type drupal-8

我正在研究Drupal 8.我希望获得内容类型的机器名称和标签.这是我的代码:

$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}
Run Code Online (Sandbox Code Playgroud)

这里我收到一条错误消息: Cannot access protected property Drupal\node\Entity\NodeType::$name

Jos*_* Jo 8

要获取当前内容类型:

$node = \Drupal::routeMatch()->getParameter('node');
$typeName = $node->bundle();
$typeLabel = $node->getTitle();
Run Code Online (Sandbox Code Playgroud)

还有另一种方法.

$node = \Drupal::request()->attributes->get('node')
Run Code Online (Sandbox Code Playgroud)


ebe*_*ent 6

<?php
  use Drupal\node\Entity\NodeType;
?>

<?php
  $all_content_types = NodeType::loadMultiple();
  /** @var NodeType $content_type */
  foreach ($all_content_types as $machine_name => $content_type) {
    $label = $content_type->label();
  }
?>
Run Code Online (Sandbox Code Playgroud)


Thi*_*Six 5

在 template_preprocess_node() 中使用此代码解决

$content_type = $node->type->entity->label();
Run Code Online (Sandbox Code Playgroud)


bai*_*kho 0

NodeType类继承了Entitylabel()的方法,使用该函数获取内容类型标签。请参阅Entity::label

$label = $value->label();
Run Code Online (Sandbox Code Playgroud)