Create/Reference a Container in Magento 2
In Magento, layouts, containers, and blocks are the basic components of the page design. Or Magento 2 uses containers and blocks to structure the layout of a page. In this post, I will demonstrate how to create/reference a container in Magento 2. To help you understand more deeply, first, I’m going to illustrate and define some important terms:
(1) A web page’s structure is represented by a layout. More specifically, using an XML file which identifies all the containers and blocks that composes the page, the web pages’ structures is provided. Layout XML files’ details will be described later.
(2) The placeholders within the webpage’s structure are represented by containers. The content structure is assigned to a page by using block tags within a layout XML file. There is no extra content, except for included elements’ content.
(3) The UI controls or components within the container placeholders are represented by blocks. By using block tags within a layout XML file, the UI elements on a page are rendered. The templates are used by blocks to generate the HTML to insert into its parent structural block. A category list, a mini cart, product listing, and product tags are included in blocks’ examples.
Now, I’m going to show you the simplest way to create/reference a container in Magento 2.
Create/Reference a Container
How to Create a Container
In order for a container to be created, you can use the following sample:
<container name="some.container" as="someContainer" label="Some Container" htmlTag="div" htmlClass="some-container" />
How to Reference a Container
For a container to be updated, use the <referenceContainer>
instruction.
Here is an example on adding links to the page hearder panel:
<referenceContainer name="header.panel">
<block class="Magento\Framework\View\Element\Html\Links" name="header.links">
<arguments>
<argument name="css_class" xsi:type="string">header links</argument>
</arguments>
</block>
</referenceContainer>
If you want to use container to wrap div or block, here is how you do it:
<container name="some.container" as="someContainer" label="Some Container" htmlTag="div" htmlClass="some-container">
<block class="Magento\Framework\View\Element\Html\Links" name="header.links">
<arguments>
<argument name="css_class" xsi:type="string">header links</argument>
</arguments>
</block>
</container>
Conclusion
I have just show you how to create and reference a container. I hope it is helpful for you. If you have any questions or new ideas, feel free to leave a comment below.
Enjoyed the tutorial? Spread it to your friends!