如何将自定义变量获取到phtml文件中


How to get a custom variable into a phtml file?

我已经从Magento 2 admin创建了一个自定义变量(系统>自定义变量)。我的自定义变量代码是";test_var";。

如何在phtml文件中获取该值?

为此,您必须使用对象管理器并使用其变量代码加载模型

之后,您可以获得它的普通值、html值和名称。

 <?php 
$model = $this->_objectManager->get('Magento'Variable'Model'Variable')->loadByCode('test_var');
$plain_value = $model->getPlainValue();
$html_value = $model->getHtmlValue();
$name = $model->getName();
?>

"干净"的方法是通过依赖项注入来实现这一点。

创建自己的区块:

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');
    }
}

并在您的.phtml文件中使用它:

<?php echo $this->getVariableValue() ?>

请使用以下代码:

$objectManager = 'Magento'Framework'App'ObjectManager::getInstance();
    $variable = $objectManager->create('Magento'Variable'Model'Variable');
    $value = $variable->loadByCode('variableCode')->getPlainValue();
    echo $value;

要获得考虑到不同商店视图的自定义变量,可以使用对象管理器:

$objectManager = 'Magento'Framework'App'ObjectManager::getInstance();
$storeManager  = $objectManager->get(''Magento'Store'Model'StoreManagerInterface');
$storeID = $storeManager->getStore()->getStoreId();
// HTML VALUE
$objectManager->get('Magento'Variable'Model'Variable')->setStoreId($storeID)->loadByCode('your_custom_variable')->getHtmlValue();
// PLAIN VALUE
$objectManager->get('Magento'Variable'Model'Variable')->setStoreId($storeID)->loadByCode('your_custom_variable')->getPlainValue();

这在magento 2.2中的phtml文件中工作:

$manager = 'Magento'Framework'App'ObjectManager::getInstance();
$value = $manager
         ->get('Magento'Framework'App'DeploymentConfig')
         ->get('shop/url') // other ex: 'db/connection/default/host'
; 
// To get the TEXT value of the custom variable:
Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('custom_variable_code')->getValue('text');
// To get the HTML value of the custom variable:
Mage::getModel('core/variable')->setStoreId(Mage::app()->getStore()->getId())->loadByCode('custom_variable_code')->getValue('html');