How to pass data from Controller to View Template files in Magento 2?

You can pass data from the Controller action to the Template files in Magento via Block Class.

You can’t directly pass controller data to view the template files but using the Block class you can achieve it successfully.

By use of the Magento interface, Magento\Framework\App\Request\DataPersistorInterface We are able to store data by key with the set(), get() method.

Check the Controller Action Code,

<?php

declare(strict_types=1);

namespace Rbj\Blog\Controller\Index;

use Magento\Framework\App\Request\DataPersistorInterface;

class PassDataToTemplate
{
    public function __construct(
        private DataPersistorInterface $dataPersistor
    ) {
    }

    public function getFormData()
    {
        return (array) $this->getDataPersistor()->set('form_data', $this->getRequest()->getParams());
    }
}

In the Controller Class, We set the data with the key name form_data and the second argument is the Request parameter.

Now You can access data from the Block Template with the get method by using key form_data,

<?php

declare(strict_types=1);

namespace Rbj\Blog\Block;

use Magento\Framework\App\Request\DataPersistorInterface;

class FormBlock
{
    public function __construct(
        private DataPersistorInterface $dataPersistor
    ) {
    }

    public function getFormData()
    {
        return (array) $this->dataPersistor->get('form_data');
    }
}

This is the way you can pass data from Block to the template by calling the method.

If you have data available in Block Class, it’s easy to fetch data to template files by just calling a specific method.

You can check the live examples from the Magento_Contact module with Post Controller.