Custom Variables In Magento 2
Custom Variables in Magento 2 let you store reusable values that can be used throughout your store to display them anywhere across the frontend or backend.
These can be simple strings, tokens, dynamic content, or formatted HTML.
We can create custom variables to store any kind of HTML code or any plain data, like any third-party base URL, which we can use to call any third-party API within the Magento 2 store.
How to create a custom variable in the admin panel
Go to Admin->System->Other Settings->Custom Variables
Next, we need to add a custom variable and its value so that we can access it anywhere throughout our store.
Now we will add our custom variable with plain value as well as html code.
We have added our custom variable to the Magento 2 admin.
Now we are going to access that variable in the frontend block.
We can do it with the code below
<?php
namespace Webkul\Demo\Block;
class Header extends \Magento\Framework\View\Element\Template
{
/**
* @var \Magento\Variable\Model\Variable
*/
protected $customvariable;
/**
* Constructor
*
* @param \Magento\Framework\View\Element\Template\Context $context
* @param \Magento\Variable\Model\Variable $customvariable
*/
public function __construct(
\Magento\Framework\View\Element\Template\Context $context,
\Magento\Variable\Model\Variable $customvariable
) {
$this->customvariable = $customvariable;
parent::__construct($context);
}
/**
* Return plain value of the variable
*
* @return string
*/
public function getPlainValue()
{
$model = $this->customvariable->loadByCode('webkul_token');
$plain_value = $model->getPlainValue();
return $plain_value;
}
/**
* Return html value of the variable
*
* @return string
*/
public function getHtmlValue()
{
$model = $this->customvariable->loadByCode('webkul_token');
$html_value = $model->getHtmlValue();
return $html_value;
}
}
We can call the above functions anywhere in the phtml file from the above block, which we have created.
The output will be like below on the homepage, with the code below
<div>
<?php echo $block->getPlainValue();?>
</div>
<div>
<?php echo $block->getHtmlValue();?>
</div>
You can read more about custom variables in Magento 2 docs:->
https://docs.magento.com/user-guide/marketing/variables-custom.html
Check for other blogs as well: https://webkul.com/blog/magento-2-layout-and-templates/
For any technical support inquiries, please email us at support@webkul.com
Browse our high-quality Magento 2 extensions created by certified Adobe Commerce developers.
For expert consultation or custom feature development, hire experienced Magento 2 developers for your project.