Magento 2 – Get Product Detail at Custom PHTML in Catalog View Layout

layoutmagento2product

I added new block to load my custom phtml inside catalog view,the problem is i need to load the current product model at my phtml, but i don't know how to do it.

app/code/Namespace/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>
    <referenceBlock name="product.info.social">
        <block class="Namespace\Module\Block\Custom" name="custom.product.view" template="Namespace_Module::custom.phtml"> </block>
    </referenceBlock>
  </body>
</page>

Best Answer

There are two way you can current product object at your custom class

First

using registry variable, In product details at every block section, you get forestry variable current_product .

Inject the registry class on you class __construct() function

 /**
 * Core registry
 *
 * @var \Magento\Framework\Registry
 */
protected $_coreRegistry;

public function __construct(
    ...
    \Magento\Framework\Registry $registry    
    ...
) {
    $this->_coreRegistry = $registry;
}

/**
 * Retrieve current product object
 *
 * @return \Magento\Catalog\Model\Product
 */
public function getProduct()
{
    return $this->_coreRegistry->registry('current_product');
}

Second

second, once extends \Magento\Catalog\Block\Product\View which @keyur already explained