Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a custom variable into a phtml file?

Tags:

php

magento2

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?

like image 704
Arun SS Avatar asked Apr 08 '16 12:04

Arun SS


3 Answers

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();
?>
like image 68
CedCommerce Avatar answered Sep 26 '22 09:09

CedCommerce


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() ?>
like image 31
Arnaud Avatar answered Sep 24 '22 09:09

Arnaud


Please use this code:

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $variable = $objectManager->create('Magento\Variable\Model\Variable');

    $value = $variable->loadByCode('variableCode')->getPlainValue();
    echo $value;
like image 45
Abhinav Kumar Singh Avatar answered Sep 22 '22 09:09

Abhinav Kumar Singh