megclaypool of Rootid
4/23/2020 - 1:54 PM

How the Hell to Get Data from Drupal in a Twig Template

Notes taken from a video chat with Jason

  • In node, paragraph, block, etc templates, content.field_whatever is a drupal render array of the content. It is not helpful for plumbing for data!!!
    • (This is what I was doing. you can see the data, but you can't get to it -- fucking everything is protected and getValue() doesn't work!)
  • You don't want to fuck with render arrays
    • Important note: You absolutely do want to use render arrays to display images and paragraphs and fields and stuff (this is the heart of Drupal's black magic), you just don't want to try to get at individual bits of data inside of them (eg: to use to toggle a conditional)
  • Most of the time, you will be given another avenue to access your field data directly
  • Note that this needs to be done in the Drupal twig template and then passed to your pattern library template!!!
  • In paragraphs, it is paragraph.field_whatever
  • In nodes, it is node.field_whatever
  • Block templates go to shit though — fieldable block templates are new to drupal, and for some stupid fucking reason that nobody can explain, it's content['#block_content'].field_whatever
  • Note: in Drupal, all fields expect to be a multivalue field. So even if a field is a single-value field, you still use paragraph.field_whatever.0
  • getValue() is the magic secret!!!
    • You can't directly access values, and not all fields store stuff in a values array anyway (eg: body summary fields). But regardless, you can call paragraph.field_whatever.0.getValue() in your twig template ← this should return an array of field values for that particular instance, whether or not it's actually stored in a values array in the database
  • Also, {{ kint(stuff) }} instead of {{ dump(stuff) }}
    • kint isn't enabled by default in Drupal but should be set up in our basic install