Hello Magento Friends,
In this article, we will focus on the most important functionality, How to Use ViewModels in Magento 2. Did you missed the previous article? No worries! It is right here. How to set NOINDEX NOFOLLOW for Specific Page in Magento 2.
With the release of Magento 2.2, there have been many improvements and one of them is the ViewModel concept. The ViewModel is a class that we insert to phtml, so that required and relevant data could be accessed from it. Avoid unwanted overriding of the block class using View Model. With the use of ViewModel, you do not need to extend the block class or add dependencies to the block. ViewModel allows passing data and additional functionality to the template file.
Let’s take a look at How to Use ViewModels in Magento 2.
Step 1: Move to the below path
app\code\Vendor\Extension\view\frontend\layout\custom_layout.xml
And add the code as follows
<block name="custom.block" template="Vendor_Module::custom.phtml"> <arguments> <argument name="viewModel" xsi:type="object">Vendor\Extension\ViewModel\Custom</argument> </arguments> </block>
Step 2: Now, navigate to the below path
app\code\Vendor\Extension\ViewModel\Custom.php
And add the below-mentioned code
<?php namespace Vendor\Extension\ViewModel; use Magento\Framework\View\Element\Block\ArgumentInterface; class Custom implements ArgumentInterface { public function getSomething() { return "Hello World"; } }
Step 3: Finally, move to the below path
app\code\Vendor\Extension\view\frontend\templates\Custom.phtml
And add the following code
<?php $viewModel = $block->getViewModel(); echo $viewModel->getSomething(); ?>
This way you can Use ViewModels in Magento 2. If you have any doubts, let me know in the comment part. Share the article with your other developer friends and stay updated with us for more.
Happy Coding!
In modern web development, seamless navigation and state management are crucial for delivering a smooth…
Magento Open Source 2.4.8 beta version released on October 8, 2024. The latest release of…
Hello Magento Friends, Creating catalog price rules programmatically in Magento 2 can be a valuable…
As the world of eCommerce continues to thrive, Shopify has become one of the most…
Shopify Remix is an innovative framework that provides a streamlined experience for building fast, dynamic,…
Building a successful eCommerce store requires expertise, and for many businesses, Shopify has become the…
View Comments
Helpful ?
How can I check the output for this
call that phtml file by binding with the layout file.