Passing variables to a child html block in Magento 2

  • At list.phtml, I am trying to get product object or product id for child template, which it comes from other module. How I can get product id at that phtml file?
    In magento 1.x it was possible via following technique. when used it into magento 2.x is throwing error

    Uncaught Error: Call to a member function setData()

    my custom module layout

    <page xmlns:xsi="" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
            <referenceBlock name="category.products.list">
                <action method="setTemplate">
                    <argument name="template" xsi:type="string">PR_Catalog::product/list.phtml</argument>
                <block class="PR\Catalog\Block\Product\Offers" name="category.products.offers" as="offer_list" template="PR_Catalog::product/offers.phtml" />

    custom module list.phtml file

    <?php    foreach ($_productCollection as $_product){ ?>
            $block->getChildBlock("offer_list")->setData("product", $_product);                            
            echo $block->getChildHtml('offer_list') 
    <?php } ?>

    block class code is

    namespace PR\Catalog\Block\Product;
    class Offers extends \Magento\Framework\View\Element\Template
        private $product;
        public function setProduct($product)
            $this->product = $product;
        public function getProduct()
          return $this->product;  

    child block phtml file

    <div class="other-offers">
       <?php echo $block->getProduct()->getId(); ?>
  • You have to define public function setProduct in your block class:

    public function setProduct($product)
        $this->product = $product;

    and then you will be able to get it in your block :)

    Also, use getChildBlock function instead of getChild

    Now you have to use your newly created function, setProduct($_product) instead of setData('product', $_product').

    still not working...

    Can you post your current code under your question?

    I have posted it.

    Check my edited answer

    we have to use `$block->getChildHtml('block_name', false);` i.e. set cache disabled.

    Yes, you are faster than me :) Without second parameter block is cached and product stays the same

    What is the final code? Could you please share?

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used