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
1 |
/* @var $block \Magento\Catalog\Block\Product\View\Options */ |
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.php. If 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.
1 2 3 4 5 6 7 8 9 10 |
<block class="Magento\Catalog\Block\Product\View\Options" name="product.info.options" as="product_options" template="Magento_Catalog::product/view/options.phtml"> <block class="Magento\Catalog\Block\Product\View\Options\Type\DefaultType" name="product.info.options.default" as="default" template="Magento_Catalog::product/view/options/type/default.phtml"/> <!-- … --> </block> <!-- … --> |
Moreover, this foreach loop can be used to display them all:
1 2 3 4 5 6 7 |
<?php echo '<pre><code>'; foreach (get_class_methods(get_class($this)) as $_method) { echo $_method; } echo '</code></pre>'; ?> |
How can a child block be assigned to another block?
In order to assign a child block, you should perform the following:
- Find out the name of the parent block where a block will be assigned;
- Add code for a child block in the local.xml file.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
<!-- for Magento 2.x: --> <referenceBlock name="catalog.topnav"> <block class="Magento\Framework\View\Element\Template" name="custom_child" template="Vendor_Module:child.phtml" /> </referenceBlock> <!-- for Magento 1.x: --> <reference name="checkout.onepage.billing"> <block type="core/template" name="custom_child" template="child.phtml" /> </reference> |
Magento 2 Development
Take your online store to the next level with BelVG Magento 2 Development
Visit the page