Viewmodel

A ViewModel can be used to retrieve customer specific logic with in a template file.

It is possible to set the viewModel argument with a layout update.

Use the snippet in the Magento 2 module creator.

Files

view/frontend/layout/test.xml

<?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="content">
			<arguments>
				<argument name="viewModel" xsi:type="object">Mage2Gen\Module\ViewModel\Test</argument>
			</arguments>
		</referenceBlock>
	</body>
</page>

ViewModel/Test.php

<?php


namespace Mage2Gen\Module\ViewModel;

class Test extends \Magento\Framework\DataObject implements \Magento\Framework\View\Element\Block\ArgumentInterface
{

    /**
     * Test constructor.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @return string
     */
    public function Test()
    {
        //Your viewModel code
        // you can use me in your template like:
        // $viewModel = $block->getData('viewModel');
        // echo $viewModel->Test();
        
        return __('Hello Developer!');
    }
}