Rendering a layout

OK, but registering a layout doesn't help us with much. Unless, of course, we use Layout Builder or some contributed module that uses layouts for various things. In which case we'd already be providing great value. But what if we want to use this layout ourselves? In other words, render stuff with it.

The simplest way of rendering something with this layout could look like this:

$layoutPluginManager = \Drupal::service('plugin.manager.core.layout'); 
$layout = $layoutPluginManager->createInstance('two_column'); 
 
$regions = [ 
  'left' => [ 
    '#markup' => 'my left content', 
  ], 
  'right' => [ 
    '#markup' => 'my right content', 
  ], 
]; 
 
return $layout->build($regions); 

Without going into too much detail about the plugin system (yet), but with the above we use the Layout plugin manager to create a new instance of the layout we defined (whose machine name is two_column). Then we prepare the data to print inside the layout in the $regions array. As you can see, the array construct mirrors the regions in the layout. Finally, we build the layout by passing the regions data. And that is it. The resulting render array would render the template with the content printed in the corresponding regions.