2

I have inserted two blocks in the catalog_product_view.xml file:

<block class="Magento\Catalog\Block\Product\View" name="product.info.custom-product-attributes" template="product/view/custom-product-attributes.phtml" after="product.info.overview"/>
...
<block class="Magento\Catalog\Block\Product\View" name="product.info.custom-estimated-delivery" template="product/view/custom-estimated-delivery.phtml" after="product.price.final"/>

How can I access a variable declared in the first block from the second block?

1

You can set the variable with register from the first phtml, then you get the value in the 2nd phtml with registry

To do things well without injecting direclty the objectManager in phtml, you have to create some function your product block, so:

In your block : app/code/Vendor/Modulename/Block/Custom.php

assuming that your variable name is : $tech

<?php
namespace Vendor\Modulename\Block;

class Custom extends \Magento\Framework\View\Element\Template
{
    protected $_coreRegistry;

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

    /**
     * Set var data
     */
    public function setTechData($data)
    {
        $this->_coreRegistry->register('tech', $data);
    }

    /**
     * Get var data
     */
    public function getTechData()
    {
        return $this->_coreRegistry->registry('tech');
    }
}

So in your First phtml :

<?php $tech = 'Your Data here'; ?>
<?php $block->setTechData($tech); ?>

In the Second phtml :

<?php $block->getTechData(); ?> //you'll get your tech value here

You can do that in phtml to test without the block solution :

First phtml :

<?php 
$tech = 'Your Data here';
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->create("Magento\Framework\Registry")->register('tech', $tech);
?>

Second phtml :

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$techData = $objectManager->create("Magento\Framework\Registry")->registry('tech');
echo $techData;
?>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.