Site icon Sudhanshu's Blog

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="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/
Layout/etc/page_configuration.xsd">
<body>
    <referenceBlock name="block.name">
        <arguments>
            <argument name="test_variable" xsi:type="string">
                I'm here at Bajaj Blog
            </argument>
        </arguments>
    </referenceBlock>
</body>
</page>

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:

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

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

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