Magento 访问模块在phtml中无处不在
我如何创建一个Magento 2模块来扩展给定的类,并能够在Magento中的每个.phtml中调用我新定义的函数 我已尝试创建我的模块这是块: etc/module.xmlMagento 访问模块在phtml中无处不在,magento,magento2,Magento,Magento2,我如何创建一个Magento 2模块来扩展给定的类,并能够在Magento中的每个.phtml中调用我新定义的函数 我已尝试创建我的模块这是块: etc/module.xml <?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Fr
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Chapagain_HelloWorld" setup_version="1.0.0" schema_version="1.0.0">
<sequence>
<module name="Magento_Footer"/>
</sequence>
</module>
</config>
Block/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_storeManager;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $data = []
)
{
$this->_storeManager = $storeManager;
parent::__construct($context, $data);
}
/**
* Get store identifier
*
* @return int
*/
public function getStoreId()
{
return $this->_storeManager->getStore()->getId();
}
/**
* Get website identifier
*
* @return string|int|null
*/
public function getWebsiteId()
{
return $this->_storeManager->getStore()->getWebsiteId();
}
/**
* Get Store code
*
* @return string
*/
public function getStoreCode()
{
return $this->_storeManager->getStore()->getCode();
}
/**
* Get Store name
*
* @return string
*/
public function getStoreName()
{
return $this->_storeManager->getStore()->getName();
}
/**
* Get current url for store
*
* @param bool|string $fromStore Include/Exclude from_store parameter from URL
* @return string
*/
public function getStoreUrl($fromStore = true)
{
return $this->_storeManager->getStore()->getCurrentUrl($fromStore);
}
/**
* Check if store is active
*
* @return boolean
*/
public function isStoreActive()
{
return $this->_storeManager->getStore()->isActive();
}
}
?>
稍后,我尝试调用footer.phtml和header.phtml中的函数(我需要它们的地方)
但Magento不允许我这么做
上面的函数不回显任何内容,函数为空。请确保扩展了正确的块。如果要扩展页眉或页脚,请查找原始位置,然后返回几个文件夹,直到找到layouts文件夹,该文件夹可浏览其中的文件,直到找到调用此模板的位置。您将看到它附加到某种块上。复制/粘贴它的名称,并将其放入“类***扩展[粘贴到此处]”中。现在可以自由编写代码了。现在,创建一个与模块中的原始布局文件同名的文件,具有相同的路径(我的意思是布局/文件夹后的路径)。使用XML setTemplate操作将块的模板替换到您的模板中(可以通过添加“您的_模块::[path to Your template after/templates folder]”来完成)。你差不多准备好了。现在打开模板覆盖并向自定义方法添加一些调用。如果所有操作都正确,您将看到正确的输出 还有一些提示:
- 不要对受保护的变量使用“\”。仅使用“storeManager”而不是“storeManager”
- 更好的类型使用[您要依赖的类]。它有助于你的代码清理。因此,不要这样:类HelloWorld extends\Magento\Framework\View\Element\Template,而是使用:使用Magento\Framework\View\Element\Template;类HelloWorld扩展模板
<?php
echo $block->getStoreId() . '<br />';
echo $block->getStoreCode() . '<br />';
echo $block->getWebsiteId() . '<br />';
echo $block->getStoreName() . '<br />';
echo $block->getStoreUrl() . '<br />';
echo $block->isStoreActive() . '<br />';
?>