Read More
Read More
Menu Close

    How to pass variable in getChildHtml in phtml file in magento 2

    Some time we need to use child block into the template file and also need pass variable in child block so we can do the below technique for resolve this problem.

    custom module layout :

    <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
        <head>
            <css src="Webkul_TimeSlotDelivery::css/style.css"/>
        </head>
        <body>
            <referenceBlock name="checkout_shipping">
                <action method="setTemplate">
                    <argument name="template" xsi:type="string">Webkul_TimeSlotDelivery::checkout/shipping.phtml</argument>
                </action>
                <block class="Webkul\TimeSlotDelivery\Block\MultiShipping\MultiShippingSlots" template="Webkul_TimeSlotDelivery::checkout/multi_shipping.phtml" name="multishipping_slots"/>
            </referenceBlock>
        </body>
    </page>

    custom module shipping.phtml file where you can set the child html block

    <div class="block block-shipping">
       <?php 
            foreach ($address as $key => $value) :
               $block->getChildBlock("multishipping_slots")->setAddress($value);
               echo $block->getChildHtml('multishipping_slots') 
            endforeach;
       ?>
    </div>

    block class code is

    <?php
    namespace Webkul\TimeSlotDelivery\Block\MultiShipping;
    
    use Magento\Framework\View\Element\Template\Context;
    
    class MultiShippingSlots extends \Magento\Framework\View\Element\Template
    {
        private $address;
    
        /**
         * @param Context $context
         * @param ProductFactory $productFactory
         * @param array $data
         */
        public function __construct(
            Context $context,
            array $data = []
        ) {
            $this->timeSlotConfig = $timeSlotConfig;
            parent::__construct($context, $data);
        }
    
    
        public function setAddress($address)
        {
            $this->address = $address;
        }
    
        public function getAddress()
        {
          return $this->address;  
        }
    }
    ?>

    Now you can use pass variable into child html template

    Start your headless eCommerce
    now.
    Read More
    $_address = $block->getAddress();

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top