我在magento 2中开发了一个示例模块,它只打印hello world。只有一个 Controller 和一个布局文件
Controller
<?php
namespace MageClass\First\Controller\Test;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
class Helloworld extends \Magento\Framework\App\Action\Action
{
public function execute()
{
$this->_view->loadLayout();
$this->_view->renderLayout();
}
}
布局文件
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<referenceBlock name="content">
<block
template="helloworld.phtml"
class="Akhil\Test\Block\Helloworld"
name="helloworld_test_helloworld">
</block>
</referenceBlock>
</page>
这里我的疑问是这个布局和 Controller 是如何链接的。当我默认通过浏览器访问 Controller 时,这个布局正在加载。它是如何链接布局和 Controller 的。
我想在我的模块中添加另一个布局和 Controller 。那么如何在访问 Controller 时链接它们加载所需的布局
最佳答案
In Magento 2 Controller and layout file linked together with their naming conventions.
因此,您在这里创建了 Controller 文件:app/code/MageClass/First/Controller/Test/Helloworld.php
您的布局文件名为:
app/code/MageClass/First/View/forntend/layout/helloworld_test_helloworld.xml
Layout file name always depends on the controller name and its action name.
布局文件的命名约定是 - modulename_controllername_actionname.xml
Example 1:
这里您的模块名称是“Helloworld”, Controller 名称是“Test”,您的操作名称是“Helloworld”。
所以你的布局文件名应该是 - helloworld_test_helloworld.xml(modulename_controllername_actionname.xml)
如果您想创建新的 Controller 和新的布局,那么现在同样的事情,那么您再次需要使用上述约定
Example :2
在这里,我正在创建第二个 Controller “Test1”和操作“Helloworld1”。
所以你的 Controller 路径应该是 - app/code/MageClass/First/Controller/Test1/Helloworld1.php
所以这里你的布局文件名应该是 - helloworld_test1_helloworld1.xml(modulename_controllername_actionname.xml)
更多引用请参阅此链接 - http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/layout-types.html
关于layout - Controller 如何在 magento 2 中加载布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40378176/