I have created a custom variable from Magento 2 admin (System > Custom Variables). My custom variable code is "test_var".
How can I get that value in a phtml file?
for this you have to use object Manager and load model using its variable Code
After that you can get its plain value, html value and its name too.
<?php
$model = $this->_objectManager->get('Magento\Variable\Model\Variable')->loadByCode('test_var');
$plain_value = $model->getPlainValue();
$html_value = $model->getHtmlValue();
$name = $model->getName();
?>
The "clean" way is to do this with dependency injection.
Create your own block:
namespace MyCompany\MyBlockName\Block;
class MyBlock extends \Magento\Framework\View\Element\Template {
protected $_varFactory;
public function __construct(
\Magento\Variable\Model\VariableFactory $varFactory,
\Magento\Framework\View\Element\Template\Context $context)
{
$this->_varFactory = $varFactory;
parent::__construct($context);
}
public function getVariableValue() {
$var = $this->_varFactory->create();
$var->loadByCode('test_var');
return $var->getValue('text');
}
}
And use it in your .phtml
file:
<?php echo $this->getVariableValue() ?>
Please use this code:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$variable = $objectManager->create('Magento\Variable\Model\Variable');
$value = $variable->loadByCode('variableCode')->getPlainValue();
echo $value;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With