11

I'm trying to get the bundle label (node type label) of the node from a node object in Drupal 8.

This works, but seems long-winded:

$node_type = \Drupal::entityManager()->getStorage('node_type')->load($node->getType())->get('name');

Is there another way to get the bundle label, possible in a less complicated way?

  • 6
    $node->type->entity->label(); is a bit more graceful maybe? I'm not sure there's a shorter version currently – Clive Apr 28 '16 at 17:13
  • 2
    Also works in twig template: {{ node.type.entity.label }} – oknate May 17 '16 at 15:22
12

The following code works, as pointed out from @Clive.

$type_name = $node->type->entity->label();
7

In case you need the node type machine name in Twig template:

{{ node.getType }}
5

Try this code.

use Drupal\node\Entity\NodeType;

$types = NodeType::loadMultiple();
$bundle = $node->bundle(); 
$type_name = $types[$bundle]->label();
  • 2
    That loads all node types just to get the label of one. a bit inefficient, better to just load the one you want. – Berdir May 13 '16 at 7:51
  • Agree! It's just base on code of @No Sssweat. – MrD May 13 '16 at 10:19
  • @Berdir thx for pointing that out. I don't want to chameleon the question, so I will leave this as the accepted answer. I am using the code in my own answer instead. – No Sssweat May 14 '16 at 10:42
5

If you want the label in twig

{{ node.type.entity.label }}
2

There is a function for that

node_get_type_label($node);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.