10

我正在研究 Drupal 8。我想获取内容类型机器名称和标签。这是我的代码:

$cont_type = node_type_get_types();
foreach ($cont_type as $key => $value) {
  $label = $value->name;
  $machine_name = $key;
}

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

4

5 回答 5

13

为了获得当前的内容类型:

$node = \Drupal::routeMatch()->getParameter('node');
$typeName = $node->bundle();
$typeLabel = $node->getTitle();

还有一种替代方法。

$node = \Drupal::request()->attributes->get('node')
于 2016-05-31T10:58:14.130 回答
7
<?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();
  }
?>
于 2016-04-29T13:06:02.510 回答
0

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

$label = $value->label();
于 2015-07-29T13:10:05.273 回答
-1

使用 {{ node.field_name.fieldDefinition.label }}

于 2019-06-06T06:09:07.727 回答
-2

请使用命名空间

use Drupal\node\Entity\Node;
于 2019-05-28T09:50:15.287 回答