layout - Controller 如何在 magento 2 中加载布局

标签 layout controller frontend magento2

我在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_tes‌​t_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/

相关文章:

html - 在 2 列或更多列中从上到下、从左到右堆叠可变高度、固定宽度的 div

android - 自定义布局作为 GridView 的项目

symfony - 在 symfony2 中寻找 Controller Action 的@transaction

java - 由 ModelAttribute 注释的多个方法。如何设置方法的调用顺序

javascript - 渲染组件时 useEffect 不触发

javascript - 带有导航(下一个,上一个)按钮的 CSS 滚动捕捉点

android - 为多种屏幕尺寸设计Android应用程序

javascript - Angularjs 使用一个 ng-model 将多个输入从 HTML 传递到 Controller

javascript - 为什么要使用 WebPack?

html - 将 <li> 拆分为两列