How to pass variables from layout to block in Magento 2 ?

Use the arguments and argument nodes. These call setData on the block. As such, you can retrieve these values later by calling the getData() method.

<?xml version="1.0"?>
<page xmlns:xsi=""
    <referenceBlock name="">
            <argument name="test_variable" xsi:type="string">
                I'm here at Bajaj Blog

Arguments values set in a layout file can be accessed in templates using the get{ArgumentName}() and has{ArgumentName}() methods. The latter returns a boolean defining whether there’s any value set. {ArgumentName} is obtained from the name attribute the following way: for getting the value of <argument name=”some_string”> the method name is getSomeString().

Example: Setting a value of css_class in the [app/code/Magento/Theme/view/frontend/layout/default.xml] layout file:

    <argument name="css_class" xsi:type="string">header links</argument>

Using the value of css_class in [app/code/Magento/Theme/view/frontend/templates/html/title.phtml]:

$cssClass = $this->hasCssClass() ? ' ' . $this->getCssClass() : '';

Leave a Reply

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