1

I was trying to access node id in twig. After debugging for a while I found that node.nid was holding the value I wanted. However, when I tried to render using that variable it didn't print anything. After struggling for while I found that I need to append .value in the end which obviously worked. But I am not sure reason behind using .value. Can someone tell me when and where should we use such?

5

Short answer: Because nid is a field and you want to get the field value.

Long answer: Node is like User or Taxonomy Term an entity and provides the method id(). So instead of accessing the id fields by their individual field name (nid, uid, tid), it's easier and better OOP practice to use the method EntityInterface::id:

{{ node.id }}
| improve this answer | |
  • Because nid is a field and you want to get the field value. Ok then how come I don't need to use .value when using content, ie {{ content.field_name }} ??? My guess is content already ran $entity->field_name->value ??? – No Sssweat Apr 12 '18 at 12:58
  • 1
    Yes, in {{ content.field_name }} are the field values, but in a render array built by the field formatter you have configured in the view mode. – 4k4 Apr 12 '18 at 14:29

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.