Magento 2, ViewModel to add a custom title in PDP

pabodah profile image Paboda Hettiarachchi ・1 min read

When there is a requirement to add an extra title in the product detail page in Magento 2, it is best to get it done via ViewModel
3 files to be edited,

  • PHP file for the ViewModel
  • layout file
  • phtml template file


namespace Vendor\Module\ViewModel;

use Magento\Framework\Registry;

class CustomTitle implements \Magento\Framework\View\Element\Block\ArgumentInterface
     * @var Registry
    protected $registry;

     * ProductTitle constructor.
     * @param Registry $registry
    public function __construct(
        Registry $registry
    ) {
        $this->registry = $registry;

     * @return mixed
    public function getOptionTitle()
        return $this->registry->registry('current_product')->getHasOptions();


<referenceContainer name="product.info.main">
    <container name="product.attribute.title.extra" as="productattributetitleextra" label="Product Attribute Title Extra" htmlTag="div" htmlClass="addon-title"  before="-">
        <block class="Magento\Framework\View\Element\Template" name="product.attribute.title.extra.template" template="Magento_Catalog::title.phtml">
                <argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\CustomTitle</argument>


/* @var $block \Magento\Framework\View\Element\Template */
<?php $viewModel = $block->getData('view_model'); ?>

 <?php if ($viewModel->getOptionTitle()): ?>
    <h2>Customized title</h2>
 <?php endif; ?>

Posted on by:

pabodah profile

Paboda Hettiarachchi


I'm a Magento programer. Like to travel and have work life balance so love to work remotely.


Editor guide

Good stuff 👌