Magento 2 set & get Registry values

The registry is getting cleared after the server sends a response. Each new request starts with an empty registry.

If you want to transfer data from one request to another you should use the session instead.


The registry will load once the controller is loaded. One more point, registry function should be called in block file only. It is the best way of doing.

So as you are calling the registry inside the controller, it wont work in that way. You need to specify block file and then you access that value to template from block. Even template definition and values should be passed through block only.

Edit:

/**
  * @var \Magento\Framework\Registry
  */

 protected $_registry;

 /**
 * ...
 * ...
 * @param \Magento\Framework\Registry $registry,
 */
public function __construct(
    ...,
    ...,
    \Magento\Framework\Registry $registry,
    ...
) {
    $this->_registry = $registry;
    ...
    ...
}

 /**
 * Setting custom variable in registry
 *
 */

public function setCustomVariable()
{
     $this->_registry->register('custom_var', 'Added Value');
}

/**
 * Retrieving custom variable from registry
 * @return string
 */
public function getCustomVariable()
{
     return $this->_registry->registry('custom_var');
}

Here you can see that I set the registry with setCustomVariable() this function and I am trying to pull the registry with this getCustomVariable().. Now we need to call this getCustomVariable() in phtml file. Now it will work.