Effective Use of the Magento Block‐Template Design System (Pt. 2)

Effective Use of the Magento Block‐Template Design System (Pt. 2)

The second part of the answers to the most frequently asked questions (click here to see Part 1).

What is the difference between a template and a block?
A template is a .phtml file containing HTML markup and PHP calls needed to display structured data. Every template is bound to a definite block and the keyword $this refers to a block. A block in its turn is an object with a PHP class assigned and a template from where data is sent.

How can I define which block methods are available in a template?
You should find a PHP class related to the template. Usually, at the beginning of a template, the class which is bound to the template is defined.

Example:

app/code/Magento/Catalog/view/frontend/templates/product/view/options.phtml:9

It’s considered to be a good style if a PHP class bound to the template is defined at the beginning. In our case, this is an Options class in the file Options.phpIf there’s lack of the comment, you can find block specifications in .xml files responsible for page layout.

For our template specifications were found in the file catalog_product_view.xml of the module Magento_Catalog. In the template attribute our template is specified, and in the class attribute, the class related to the template is defined.

Moreover, this foreach loop can be used to display them all:

How can a child block be assigned to another block?
In order to assign a child block, you should perform the following:

  1. Find out the name of the parent block where a block will be assigned;
  2. Add code for a child block in the local.xml file.

Example:



Post a new comment

top