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.

Steps 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

Step 2: Now, navigate to the below path

app\code\Vendor\Extension\ViewModel\Custom.php

And add the below-mentioned code

Step 3: Finally, move to the below path

app\code\Vendor\Extension\view\frontend\templates\Custom.phtml

And add the following code

Conclusion:

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!

Click to rate this post!
[Total: 9 Average: 4.3]