This topic discusses the main concepts of how default templates work in the Magento 2 application. The following topics are covered:

  • How templates are initiated
  • Root template
  • Conventional templates location
  • Templates overriding
  • Getting argument values from layout

How Magento 2 templates are initiated

Magento 2 templates are usually initiated in layout files. Each layout block has an associated template. The template is specified in the template attribute of the layout instruction. For example, from <Magento_Catalog_module_dir>/view/frontend/layout/catalog_category_view.xml:

<block class="Magento\Catalog\Block\Category\View" name="category.image" template="Magento_Catalog::category/image.phtml"/>

This means that the category.image block is rendered by the image.phtml template, which is located in the category subdirectory of the Magento_Catalog module templates directory.

The templates directory of Magento_Catalog is <Magento_Catalog_module_dir>/view/frontend/templates.

The next section describes where templates can be located in general.

Magento 2 Conventional templates location

Templates are stored in the following locations:

  • Module templates: <module_dir>/view/frontend/templates/<path_to_templates>
  • Theme templates: <theme_dir>/<Namespace>_<Module>/templates/<path_to_templates>

Here <path_to_templates> might have several levels of directory nesting, or might be empty. Examples:

  • <Magento_Catalog_module_dir>/view/frontend/templates/product/widget/new/content/new_grid.phtml
  • <Magento_Checkout_module_dir>/view/frontend/templates/cart.phtml

Magento 2 Templates overriding

For template files with the same name, the following is true: theme templates override module templates, and those of a child theme override parent theme templates.

This mechanism is the basis of the template customization concept in Magento2 application: to change the output defined by a certain default template, you need to override one in your custom theme.

Overriding templates is described with more details in the Theme Inheritance article.

Magento 2 Root template

In Magento 2 there’s a special template which serves as root template for all storefront pages in the application:<Magento_Theme_module_dir>/view/base/templates/root.phtml.

Unlike other templates, root.phtml contains the doctype specification and contributes to <head> and <body> sections of all pages rendered by Magento application. But similar to other templates, root.phtml can be overridden in a theme.

Getting argument values from layout

Arguments values set in a layout file can be accessed in templates using the get{ArgumentName}() and has{ArgumentName}()methods. There are more details in the Layout instructions article.

0 Likes
538 Views

You may also like

Leave A Comment

Please enter your name. Please enter an valid email address. Please enter message.