YAML formatting and Drupal 8 - making things readable

As someone who loves YAML syntax (so much more pleasant to work with than JSON!), I wanted to jot down a few notes about syntax formatting for the benefit of Drupal 8 developers everywhere.

I often see copy/pasted YAML examples like the following:

  child-object: {key: value, key2: {key: value}}

This is perfectly valid YAML. And technically any JSON is valid YAML too. That's part of what makes YAML so powerful—it's easy to translate between JSON and YAML, but YAML is way more readable!

So instead of using YAML like that, you can make the structure and relationships so much more apparent by formatting it like so:

    key: value
      key: value

This format makes it much more apparent that both key and key2 are part of child-object, and the last key: value is part of key2.

In terms of Drupal, I see the confusing { } syntax used quite often in themes and library declarations. Take, for instance, a library declaration that adds in some attributes to an included JS file:

https://some-api.com/?key=APIKEY&signed_in=true: {type: external, attributes: { defer: true, async: true} }

That's difficult to read at a glance—and if you have longer key or value names, it gets even worse!

Instead, use the structured syntax for a more pleasant experience (and easier git diff ability):

  type: external
    defer: true
    async: true

You really only need to use the { } syntax for objects if you're defining an empty object (one without any keys or subelements):

# Objects.
  key: value
empty-object: { }

# Arrays.
  - item
empty-array: [ ]

I've worked with a lot of YAML in the past few years, especially in my work writing Ansible for DevOps. It's a great structured language, and the primary purpose is to make structured data easy to read and edit (way, way simpler than JSON, especially considering you won't need to worry about commas and such!)—so go ahead and use that structure to your advantage!


In you opening example you are inconsistent in the use of child-object vs something-else.

Fixed, thanks!

Now there's no something-else entry in your initial example...

And thank you for raising awareness of readability and YAML. It's super-easy to turn YAML into obscure, Perl-like code. I think people get so worried about the whitespace-delimited formats that they avoid adding comments or extra newlines to separate logical chunks. Unfortunately, Drupal core is not leading by example here...

Fixed, thanks!