Skip to content
intermediate Phase 54 · Frontend Components

Blocks and Templates

Understanding Magento 2 block classes, template variables, escape methods, and template inheritance patterns

45m
0 problems
Topic Progress 0%

Block Class Architecture

Template Block Base Class

<?php
namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;

class ProductList extends Template
{
    public function __construct(
        Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }
}

Block with Dependencies

<?php
namespace Vendor\Module\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\View\Element\Template\Context;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Registry;

class ProductList extends Template
{
    public function __construct(
        Context $context,
        private CollectionFactory $productCollectionFactory,
        private Registry $registry,
        array $data = []
    ) {
        parent::__construct($context, $data);
    }
}

Block Lifecycle Methods

public function _prepareLayout(): void
{
    // Set page title, meta info, breadcrumbs
    $this->pageConfig->getTitle()->set(__('Product List'));
    parent::_prepareLayout();
}

public function _toHtml(): string
{
    // Before rendering
    return parent::_toHtml();
}

public function getCacheKeyInfo(): array
{
    // Custom cache key
    return [
        'PRODUCT_LIST',
        $this->getStoreManager()->getStore()->getId()
    ];
}

Template Variables

Passing Data to Templates

Via Block Methods

// In Block
class ProductList extends Template
{
    public function getProducts(): array
    {
        return ['Product 1', 'Product 2', 'Product 3'];
    }
    
    public function getTitle(): string
    {
        return $this->getData('title') ?? 'Products';
    }
}

In Template

<!-- product_list.phtml -->
<?php
/** @var Vendor\Module\Block\ProductList $block */
$products = $block->getProducts();
$title = $block->getTitle();
?>
<h1><?= $block->escapeHtml($title) ?></h1>
<ul>
    <?php foreach ($products as $product): ?>
        <li><?= $block->escapeHtml($product) ?></li>
    <?php endforeach; ?>
</ul>

Via Layout XML Arguments

<block class="Vendor\Module\Block\ProductList"
       name="product.list"
       template="product/list.phtml">
    <arguments>
        <argument name="title" xsi:type="string">Featured Products</argument>
        <argument name="limit" xsi:type="number">10</argument>
        <argument name="show_price" xsi:type="boolean">true</argument>
    </arguments>
</block>

Accessing Arguments

public function getLimit(): int
{
    return (int)$this->getData('limit');
}

public function shouldShowPrice(): bool
{
    return (bool)$this->getData('show_price');
}

Escape Methods

Complete Escape Method Reference

// HTML body context
echo $block->escapeHtml($text);

// Allow specific tags
echo $block->escapeHtml($richText, ['b', 'i', 'em', 'strong']);

// HTML attributes
echo $block->escapeHtmlAttr($attributeValue);

// URLs
echo $block->escapeUrl($url);

// CSS
echo $block->escapeCss($cssValue);

// JavaScript
echo $block->escapeJs($jsString);

// JSON
echo $block->escapeJson($jsonString);

// Quote
echo $block->escapeQuote($stringValue);

Context-Specific Escaping

Context Method Example
HTML body escapeHtml() <p><?= $block->escapeHtml($text) ?></p>
HTML attribute escapeHtmlAttr() alt="<?= $block->escapeHtmlAttr($alt) ?>"
URL escapeUrl() href="<?= $block->escapeUrl($url) ?>"
CSS escapeCss() style="<?= $block->escapeCss($style) ?>"
JavaScript escapeJs() var x = '<?= $block->escapeJs($val) ?>';

Common Mistakes

// WRONG: No escaping
echo $product->getName();

// WRONG: Wrong context
echo $block->escapeHtml($url);  // URL in href attribute

// RIGHT: Match context
echo $block->escapeUrl($url);  // For URLs

// RIGHT: HTML in allowed context
echo $block->escapeHtml($description, ['p', 'br', 'strong']);

Template Inheritance

Template Layout Inheritance

<!-- parent.phtml (layout) -->
<container name="page.wrapper" htmlTag="div" htmlClass="wrapper">
    <block name="header" template="header.phtml"/>
    <block name="content" template="content.phtml"/>
    <block name="footer" template="footer.phtml"/>
</container>

PHP Template Inheritance

<!-- parent.phtml -->
<html>
<body>
    <header><?= $block->getChildHtml('header') ?></header>
    <main><?= $block->getChildHtml('content') ?></main>
    <footer><?= $block->getChildHtml('footer') ?></footer>
</body>
</html>

<!-- child.phtml -->
<?php $this->extend('parent.phtml') ?>

<?php $this->blockContent('content') ?>
    <div class="custom-content">
        <?= $block->escapeHtml($block->getCustomContent()) ?>
    </div>
<?php $this->blockContent() ?>

Child Block Rendering

// Get specific child block
$childBlock = $block->getChildBlock('child.name');
echo $childBlock->toHtml();

// Render all children
echo $block->getChildHtml();

// Render specific child
echo $block->getChildHtml('child.name');

// Render in order
echo $block->getChildHtml('', true, ',');

Adding Children Programmatically

public function _prepareLayout(): void
{
    $this->setChild('custom_block',
        $this->getLayout()->createBlock(
            \Vendor\Module\Block\Custom::class,
            'custom_block_name'
        )
    );
    parent::_prepareLayout();
}

Quiz

1. What is the base class for template blocks?

Question 1 options

2. Which method escapes HTML for safe output?

Question 2 options

3. How do you render a specific child block?

Question 3 options

Flashcards

Question

What is the template block base class?

Answer

Magento\Framework\View\Element\Template

Question

How do you escape HTML?

Answer

$block->escapeHtml($text)

Question

How do you escape URLs?

Answer

$block->escapeUrl($url)

Question

How do you render all child blocks?

Answer

$block->getChildHtml()

Question

Where do you set page title in block?

Answer

_prepareLayout() method

Revision Notes

Key Takeaways

  • 1. Blocks extend Template and prepare data for .phtml templates
  • 2. Always escape output using context-appropriate methods
  • 3. Use _prepareLayout() for page configuration
  • 4. Child blocks are rendered with getChildHtml()
  • 5. Template inheritance uses extend() and blockContent()

Interview Tips

  • Explain the block lifecycle and key methods
  • Know all escape methods and their contexts
  • Discuss template inheritance patterns
  • Be ready to create blocks with dependencies

Cheat Sheet

Base class: Template
Constructor: Context $context, array $data

Escape methods:
  escapeHtml()     - HTML body
  escapeHtmlAttr() - Attributes
  escapeUrl()      - URLs
  escapeCss()      - CSS
  escapeJs()       - JavaScript

Child blocks:
  getChildHtml('name')
  getChildBlock('name')