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
Next we need to add custom variable and its value so that we can access it anywhere through out our store.
Now we will add our custom variable with plain value as well as html code.
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>
You can read more about custom variables in Magento2 docs:->
https://docs.magento.com/user-guide/marketing/variables-custom.html
Be the first to comment.