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
app/code/Vendor/Module/ViewModel/CustomTitle.php
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();
}
}
app/design/frontend/Vendor/default/Magento_Catalog/layout/catalog_product_view.xml
<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">
<arguments>
<argument name="view_model" xsi:type="object">Vendor\Module\ViewModel\CustomTitle</argument>
</arguments>
</block>
</container>
</referenceContainer>
app/design/frontend/Vendor/default/Magento_Catalog/templates/title.phtml
<?php
/* @var $block \Magento\Framework\View\Element\Template */
?>
<?php $viewModel = $block->getData('view_model'); ?>
<?php if ($viewModel->getOptionTitle()): ?>
<h2>Customized title</h2>
<?php endif; ?>
Top comments (1)
Good stuff π