Lesson6: Templates in magento2

0
54

This topic explains how default templates work in the Magento application.

I. Templates.

1. What components can templates be found in?

● Modules
● Themes

2. What is the file structure of template files?

● Modules
view/<area>/templates/some/path/file.phtml
● Themes
<Vendor_Module>/templates/some/path/file.phtml

II. Block classes.

1. What is the default block class for use with templates?

Magento\Framework\View\Element\Template

2. What block class do all others extend from?

Magento\Framework\View\Element\AbstractBlock

III. Block data.

1. How do you access the block from a template?

● Using the $block variable
$this should not be used

2. How do you call block methods or get data?

<some-file>.phtml

Block data magento 2

IV. Block methods.

1. What are common block methods?

<some-file>.phtml

block method in magento2

2. How do child blocks work?

<some_handle>.xml

block methods magento2

my-template.phtml

template magento2

<some-file>.phtml

template magento2

<some-file>.phtml

template magento2

3. How do you output a group of child blocks?

● Using the group attribute in layout and the getGroupChildNames method in the parent template
● Requires custom implementation
● Product detail page tabs are best example in Magento core codebase

<some_handle>.xml

block method in magento2

group.phtml

block-template magento2

V. Best practice.

1. What should / shouldn’t templates contain?

Should:
○ View / presentation markup
○ Data and basic conditions / constructs (if / foreach)
○ Translated strings
 Shouldn’t:
○ Business logic
○ Excessive file contents

2. What is <?=?

● PHP short echo tag
Equivalent to <?php echo
● Magento uses <?=

3. What is the recommended format for PHP control structures in templates? (ifs, loops etc.)

● Standard PHP control structures should NOT be used
e.g. ifs or loops with curly braces
● Use alternative control structures at ALL TIMES
http://php.net/manual/en/control-structures.alternative-syntax.php

<some-file>.phtml

practice template magento2

<some-file>.phtml

practice template magento2