我已经从magento 2 admin(系统>自定义变量)创建了一个自定义变量。我的自定义变量代码是" test_var"。
如何在phtml文件中获取该值?
答案 0 :(得分:6)
为此,您必须使用对象管理器并使用其变量代码
加载模型之后你也可以得到它的普通值,html值和它的名字。
<?php
$model = $this->_objectManager->get('Magento\Variable\Model\Variable')->loadByCode('test_var');
$plain_value = $model->getPlainValue();
$html_value = $model->getHtmlValue();
$name = $model->getName();
?>
答案 1 :(得分:3)
“干净”的方式是通过依赖注入来做到这一点。
创建自己的块:
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() ?>
答案 2 :(得分:3)
请使用此代码:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$variable = $objectManager->create('Magento\Variable\Model\Variable');
$value = $variable->loadByCode('variableCode')->getPlainValue();
echo $value;
答案 3 :(得分:1)
要获取自定义变量考虑到不同的商店视图,可以使用对象管理器:
$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();
答案 4 :(得分:0)
// 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');
答案 5 :(得分:0)
这在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'
;
答案 6 :(得分:0)
我们在Stenik小组开发了满足您需求的magento 2模块,该模块将帮助您从任何phtml模板访问自定义变量:Download
答案 7 :(得分:0)
添加到 Arnaud 的答案中,使用 $var->validate() === TRUE
检查代码。