Reading list Switch to dark mode

    Custom Variables In Magento2

    Updated 6 July 2022

    We can create custom variables to store any kind of html code or any kind of plain data like any third party base URL which we can use to call any third party API with in the magento2 store.

    How to create custom variable in admin panel

    Go to Admin->System->Other Settings->Custom Variables

    page

    Next we need to add custom variable and its value so that we can access it anywhere through out our store.

    Custom-Variables-Other-Settings-System-Magento-Admin

    Now we will add our custom variable with plain value as well as html code.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    1
    2

    we have added our custom variable to Magento2 admin.

    Now we are going to access that variable in frontend block.

    We can do it with below code

    <?php
    namespace Webkul\Demo\Block;
    class Header extends \Magento\Framework\View\Element\Template
    {
    	protected $customvariable;
    	public function __construct(
    		\Magento\Framework\View\Element\Template\Context $context,
    		\Magento\Variable\Model\Variable $customvariable
    	)
    	{
    		$this->customvariable = $customvariable;
    		parent::__construct($context);
    	}
    
    	public function getPlainValue()
    	{
    		$model = $this->customvariable->loadByCode('webkul_token');
    		$plain_value = $model->getPlainValue();
    		return $plain_value;
    	}
    
    	public function getHtmlValue(){
    
    		$model = $this->customvariable->loadByCode('webkul_token');
    		$html_value = $model->getHtmlValue();
    		return $html_value;
    	}
    }

    we can call above functions anywhere in phtml file from the above block which we have created.

    The output will be like below in homepage with below code

    <?php echo $block->getPlainValue();?>
    
    <div>
        <?php echo $block->getHtmlValue();?>
    </div>
    3

    You can read more about custom variables in Magento2 docs:->

    https://docs.magento.com/user-guide/marketing/variables-custom.html

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home