Skip to content
intermediate Phase 15 · Routing & Areas

Magento 2 Frontend Area

Frontend area specifics - layout handles, themes, blocks, templates, and JavaScript components.

45m
0 problems
Topic Progress 0%

Frontend Area Loading Process

The frontend area is the most common area in Magento, handling all customer-facing storefront requests. When a frontend request arrives, the area resolver sets the area code to frontend before the controller action executes.

The frontend loading sequence:

  1. Area code set - Magento\Framework\App\Area\Resolver\HttpResolver detects frontend URL
  2. Configuration loaded - Global + frontend-specific di.xml merged
  3. Theme resolved - Active theme determined from store configuration
  4. Layout loaded - Layout XML files processed for the page
  5. Blocks instantiated - Block classes created from layout definitions
  6. Templates rendered - PHP/HTML templates output block content

Frontend-specific configuration location:

app/code/Vendor/Module/etc/frontend/
├── di.xml           # Frontend DI configuration
├── routes.xml       # Frontend route definitions
├── events.xml       # Frontend-only observers
├── layout.xml       # Layout file declarations
└── page_layout.xml  # Page layout updates

Example frontend di.xml:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Catalog\Block\Product\ListProduct">
        <arguments>
            <argument name="toolbar" xsi:type="object">
                Vendor\Module\Block\Product\CustomToolbar
            </argument>
        </arguments>
    </type>
</config>

Layout Handles in the Frontend

Layout handles are unique identifiers that determine which layout XML files are loaded for a specific page. Each page request receives multiple handles that define its layout structure.

Default handles applied to every page:

  • default - Always loaded first
  • root - Base page structure

Route-based handles:

  • {routeName}_{controllerName}_{actionName} - e.g., catalog_product_view

Page-specific handles:

  • cms_index_index - CMS homepage
  • catalog_category_view - Category page
  • catalog_product_view - Product page

Layout handle example:

<!-- app/code/Vendor/Module/view/frontend/layout/catalog_product_view.xml -->
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Vendor\Module\Block\Product\CustomInfo"
                   name="product.custom.info"
                   template="Vendor_Module::product/custom_info.phtml"
                   after="-"/>
        </referenceContainer>
    </body>
</page>

Custom layout handles can be added programmatically:

public function addCustomHandle($observer)
{
    $layout = $observer->getEvent()->getLayout();
    $layout->getUpdate()->addHandle('custom_product_handle');
}

Layout handles enable precise control over which blocks appear on specific pages without conditional logic in templates.

Themes, Blocks, and Templates

The frontend area is built on three pillars: themes (visual identity), blocks (logic containers), and templates (presentation).

Theme Structure:

app/design/frontend/Vendor/theme/
├── registration.php
├── theme.xml
├── etc/
│   └── view.xml          # Module-specific view config
├── web/
│   ├── css/              # Stylesheets
│   ├── js/               # JavaScript files
│   ├── images/           # Image assets
│   └── fonts/            # Font files
└── Magento_Catalog/
    └── templates/
        └── product/
            └── list.phtml

Block Class Example:

<?php
namespace Vendor\Module\Block\Product;

class CustomInfo extends \Magento\Catalog\Block\Product\View
{
    protected $_template = 'product/custom_info.phtml';
    
    public function getCustomAttribute()
    {
        $product = $this->getProduct();
        return $product->getData('custom_attribute');
    }
    
    public function isSpecialDisplay()
    {
        return $this->_scopeConfig->getValue(
            'vendor_module/display/special_mode',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }
}

Template File:

<?php
/** @var Vendor\Module\Block\Product\CustomInfo $block */
?>
<div class="custom-product-info">
    <?php if ($block->isSpecialDisplay()): ?>
        <span class="special-badge">Special</span>
    <?php endif; ?>
    <p>Custom: <?= $block->escapeHtml($block->getCustomAttribute()) ?></p>
</div>

Frontend JavaScript Components

Magento 2 frontend uses a RequireJS-based module system for JavaScript. Components are registered in requirejs-config.js and loaded on demand.

RequireJS configuration:

// app/code/Vendor/Module/view/frontend/requirejs-config.js
var config = {
    map: {
        '*': {
            'customComponent': 'Vendor_Module/js/custom-component',
            'catalogAddToCart': 'Vendor_Module/js/catalog-add-to-cart'
        }
    },
    paths: {
        'vendorModule': 'Vendor_Module/js'
    }
};

JavaScript component:

// view/frontend/web/js/custom-component.js
define([
    'jquery',
    'uiComponent',
    'mage/url'
], function ($, Component, urlBuilder) {
    'use strict';
    
    return Component.extend({
        defaults: {
            template: 'Vendor_Module/custom-component'
        },
        
        initialize: function () {
            this._super();
            this.loadData();
            return this;
        },
        
        loadData: function () {
            var self = this;
            $.ajax({
                url: urlBuilder.build('vendormodule/index/data'),
                type: 'GET',
                dataType: 'json',
                success: function (response) {
                    self.setData(response);
                }
            });
        }
    });
});

Knockout template:

<!-- view/frontend/web/template/custom-component.html -->
<div data-bind="if: isVisible">
    <span data-bind="text: message"></span>
</div>

JavaScript components can be added to blocks via XML layout:

<block class="Magento\Framework\View\Element\Template" name="custom.js">
    <arguments>
        <argument name="jsLayout" xsi:type="array">
            <item name="components" xsi:type="array">
                <item name="custom" xsi:type="array">
                    <item name="component" xsi:type="string">Vendor_Module/js/custom-component</item>
                </item>
            </item>
        </argument>
    </arguments>
</block>

Quiz

1. What is a layout handle in Magento 2?

Question 1 options

2. Where do frontend JavaScript component configurations go?

Question 2 options

3. What naming convention do layout files follow for a route?

Question 3 options

Flashcards

Question

What resolver sets the frontend area code?

Answer

Magento\Framework\App\Area\Resolver\HttpResolver

Question

What is the default layout handle applied to every page?

Answer

default

Question

Where do module templates go in a theme?

Answer

app/design/frontend/Vendor/Theme/{Module}/templates/

Question

What JS framework does Magento 2 use for frontend components?

Answer

RequireJS for module loading, Knockout.js for MVVM binding

Revision Notes

Key Takeaways

  • 1. Frontend area handles all customer-facing storefront requests
  • 2. Layout handles determine which XML files load for each page
  • 3. Themes provide visual identity, blocks provide logic, templates provide presentation
  • 4. JavaScript uses RequireJS module system with Knockout.js for binding
  • 5. Frontend-specific config goes in etc/frontend/ within modules
  • 6. Custom layout handles can be added programmatically via observers

Interview Tips

  • Explain the page rendering process from URL to HTML output
  • Describe how layout handles work and give examples
  • Discuss the relationship between themes, blocks, and templates
  • Explain how Magento 2 loads JavaScript components on demand
  • Know the difference between frontend and base view.xml

Cheat Sheet

Frontend Area Cheat Sheet

Config Path: etc/frontend/
Theme Path: app/design/frontend/{Vendor}/{Theme}/
Templates: {Theme}/{Module}/templates/
JS Config: requirejs-config.js

Layout Handles:

  • default - Every page
  • {route}_{controller}_{action} - Route-specific
  • cms_page_view - CMS pages
  • catalog_product_view - Product pages

Block Hierarchy:

  • root → header → content → footer
  • Reference containers to add/modify blocks