Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 42 ยท Requests and Output

Layout XML and Handles

Understand Magento layout handles, containers versus blocks, referenceBlock, move, remove and update, and how layout files merge into one page structure.

A Magento page is not one big template. It is a tree of containers and blocks, and that tree is described in XML files called layout files. Your controller returns a page result; the framework then collects the right layout files, merges them, builds the tree, and renders it. This design is why a module can add a banner to the header of every page without touching the theme, and why a theme can remove a block that a module added.

In this lesson you will learn the vocabulary (handles, containers, blocks), the instructions you can write in layout XML, and how merging works. Real Magento layout files are shown read-only. A small runnable processor then merges layouts and prints the resulting tree, so you can watch referenceContainer, move and remove do their work.

Handles pick the files

A handle is a name for a situation. When a page is built, Magento works out a list of handles that apply, and then loads every layout file whose name matches one of them. Layout files live in a module's view/<area>/layout/ folder (for example view/frontend/layout/) and are named after the handle: catalog_product_view.xml.

Handles come from several places:

  • default applies to every page.
  • The action handle is built from the route: <route id>_<controller folder>_<action>. The route from Routing and Controllers with id acme_hello and the action Greeting/Show yields acme_hello_greeting_show.
  • Context handles such as customer_logged_in or customer_logged_out, depending on the visitor.
  • Entity handles on product pages, such as catalog_product_view_type_simple for the product type or one that includes the product ID.
  • Page layout handles such as 1column or 2columns-left, chosen with the layout attribute of the page.
  • Handles you pull in with <update handle="..."/>.

Because every module may have a file with the same handle name, the final layout for default is the merge of all those files. Order follows module load order (see Module Sequence and Dependencies), then the active theme's files. That is the same merging idea you saw in Areas and Configuration Files, applied to layouts.

flowchart TD
    A["Page request<br/>acme_hello/greeting/show"] --> B["Collect handles<br/>default, acme_hello_greeting_show, ..."]
    B --> C["Find every layout file<br/>for each handle<br/>(modules, then theme)"]
    C --> D["Merge into one XML"]
    D --> E["Build the tree<br/>containers + blocks"]
    E --> F["Render templates<br/>into HTML"]

Handles select layout files; the files are merged, turned into a tree and rendered.

Containers and blocks

Two kinds of elements make up the tree:

  • A container has no PHP class and no template. It exists to hold other elements and to output an optional wrapper such as <div class="columns">. Examples are the page content area and the header.container.
  • A block is backed by a PHP class (the default Magento\Framework\View\Element\Template if you omit one) and usually renders a .phtml template. Blocks can also hold children.

A layout file that adds a block to the content area looks like this:

XML
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Acme\Hello\Block\Greeting"
                   name="acme.greeting"
                   template="Acme_Hello::greeting.phtml"/>
        </referenceContainer>
    </body>
</page>

The name must be unique across the whole merged layout, so use a vendor-style prefix. The template value is Module_Name::path/in/templates.phtml, found in view/<area>/templates/. The next lesson, Blocks, ViewModels and PHTML Templates, covers what happens inside.

The instructions you can write

Layout XML has a small set of instructions. These are the ones you will use daily:

Instruction What it does
<container name="x"> Declare a new container. Options include htmlTag, htmlClass and label.
<block class name template> Declare a new block.
<referenceContainer name="x"> Open an existing container to add children or change it.
<referenceBlock name="x"> Open an existing block to change its arguments or children.
remove="true" on a reference Remove that element from the page.
<move element dest> Move an element to another parent.
<update handle="x"/> Include everything from another handle.
<argument name xsi:type> Pass data into a block, readable in the block and template.

Positioning uses before and after. The value is a sibling's name, or -, which means "first" for before and "last" for after:

XML
<referenceContainer name="header.container">
    <block class="Acme\Banner\Block\Banner" name="acme.banner"
           template="Acme_Banner::banner.phtml" before="-"/>
</referenceContainer>

Removing and moving look like this:

XML
<referenceBlock name="copyright" remove="true"/>
<move element="top.search" destination="content" after="-"/>

Prefer referenceBlock ... remove="true" over editing core templates. Some blocks are also hidden without being deleted, using a display="false" attribute on a reference; the effect is similar, but the block stays addressable by others. Check the layout XML of your Magento version for the exact options before you rely on them.

A few other facts keep you out of trouble:

  • You can only reference an element that has been declared by the time your instruction is processed, so a module that references another module's block should list it in its sequence.
  • <update handle="..."> is how a handle reuses work. Product pages of several types, for instance, can pull in shared layout.
  • Layout is cached in production, so a changed layout file is only visible after cache cleaning (see Indexers and Caching).

Themes and layout

Themes can also provide layout files. A theme file with the same handle is merged with the module files, so a theme can add or remove blocks. Magento also has special override folders for replacing a file entirely. Both are part of the theme system in The Theme System and Frontend Assets. The safe default is to extend, not to replace: a replacement hides every future change that the original file would get from upgrades.

Try it: a tiny layout processor

This stand-in reads layout XML from several sources, merges them for a list of handles, applies referenceContainer, referenceBlock, move, remove and update, and prints the tree. It is a teaching model: real Magento adds argument handling, caching, ACL checks, page-layout files and many more rules. The files below mimic a base page, an extra module for default, and a product-page file.

PHP Merging layout files and building the tree

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Compare the two trees. On the home page the banner from Acme_Banner comes first in the header because of before="-". On the product page the search block has moved into the content container, the copyright block is gone, and the sidebar container appeared because catalog_product_view pulled in the sidebar_promo handle with update.

A second small stand-in shows how an action name becomes the handle list. Real Magento adds more context handles than this, so treat the result as an illustration.

PHP From route to a list of handles

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real Magento computes handles from more sources (the store, the product type, page layouts), so treat the function as an illustration of the naming pattern: route_folder_action, plus suffixes for entity details.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a layout handle?

    Handles such as default or catalog_product_view select layout files, which are merged from all modules and the theme.
  2. 2. What is the difference between a container and a block?

    A container only groups elements and can output a wrapper tag. A block is backed by a class and normally renders a PHP template.
  3. 3. Which instruction removes a block that another module added?

    Reference the existing block by name and set remove to true. Editing another module's file is the wrong approach.
  4. 4. What does before="-" mean on a child element?

    A dash with before means first. A dash with after means last.
  5. 5. What is the action handle for route id acme_hello and the action Greeting/Show?

    The handle joins route id, controller folder and action name with underscores, all lowercase.

Summary

  • Handles name situations; Magento loads every layout file with a matching name and merges them.
  • Containers group elements; blocks have classes and templates. Names must be unique across the merged layout.
  • referenceContainer and referenceBlock modify existing elements; remove="true", move and update reshape the tree.
  • Use before and after (with - for first or last) to position elements.
  • Extend layouts rather than replace them, and clear caches to see changes in production-like modes.

Next, see what happens inside a block in Blocks, ViewModels and PHTML Templates.