ViewModel in Magento 2

If you want to inject code in template file without using block class function or helper function, then you can use ViewModel.

The use of helpers in templates is not recommended instead we can use ViewModel.

For example, if your want to display customer attribute on my account page in customer info section.

Step 1: Create customer_account.xml in your custom module and place below code-

<?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="customer_account_dashboard_info">

<action method="setTemplate">

<argument name="template" xsi:type="string">Vendorname_Modulename::account/dashboard/info.phtml</argument>

</action>

<arguments>

<argument name="viewModel" xsi:type="object">Vendorname\Modulename\ViewModel\CustomerAttribute</argument>

</arguments>

</referenceBlock>

</body>

</page>

Step 2: Create template file info.phtml.

Step 3: Create viewmodel for added code into your template file