Simply put, layouts are plugins. But unlike the plugins we've seen before, these are defined in YAML files instead of annotations above a class. One of the reasons for this is that layouts are more definition than functionality, so they don't necessarily require classes. They can be simply defined in a few lines inside a YAML file.
Although not necessarily, YAML-based plugins are typically defined inside a file named module_name.plugin_type_name.yml found in the root of the module defining the plugin. So in the case of layouts, this would be module_name.layouts.yml. But what does a definition contain?
Let's imagine we want to define a two-column layout with a left and right region. Our simplest definition could look like this:
two_column: label: 'Two column' category: 'My Layouts' template: templates/two-column regions: left: label: Left region right: label: Right region
So what do we learn from this definition?
- First, we have a name and category, which are mandatory. These can be used in whatever UI to show information about the layout.
- Second, we specify the template that should render this layout. The corresponding theme hook gets defined under the hood. In the case above, the template file would be in the templates folder and would be called two-column.html.twig.
- Lastly, we define the regions of the layout with a label for each. The left and right keys are important as they are the machine names of the regions.
- As a bonus, if we wanted to attach a library, we could add another line to this definition, like so:
library: my_module/my_library
Before the layout registration was complete, we'd also need to create the template file we referenced. And it could look like this:
<div class="two-column"> <div class="left-region"> {{ content.left }} </div> <div class="right-region"> {{ content.right }} </div> </div>
In the template we have access to the content variable on which we can access the values of the regions we can print.
And that's pretty much it. Clearing the cache (and enabling the Layout Discovery module) would register this layout with the system.