在phtml文件中获取magento 2自定义变量

Aru*_* SS 4 magento magento2 magento-2.0 magento2.0.2

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

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

小智 6

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

之后,您可以获得其普通值,html值及其名称.

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

  • 像这样使用对象管理器通常是不受欢迎的。您可能应该在块逻辑中编写它并使用 getter 进行依赖注入。这是一篇关于如何做到这一点的文章。http://devdocs.magento.com/guides/v2.0/extension-dev-guide/depend-inj.html#injection-types-used-in-magento (2认同)

Arn*_*aud 6

“干净”的方法是通过依赖项注入来实现。

创建自己的块:

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

}
Run Code Online (Sandbox Code Playgroud)

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

<?php echo $this->getVariableValue() ?>
Run Code Online (Sandbox Code Playgroud)


Sun*_*hod -1

// 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');
Run Code Online (Sandbox Code Playgroud)

  • 此响应适用于 Magento1,而不是所要求的 Magento2。 (4认同)