To display "Hello World" on your own page in Magento 2, follow these steps:
1. Register a router for the storefront.
Create this file:
app/code/<VendorName>/<ModuleName>/etc/frontend/routes.xml
and add the following code there:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="VendorName_ModuleName" frontName="path">
<module name="VendorName_ModuleName" />
</route>
</router>
</config>
You can use the developer name (VendorName) associated with the module name (ModuleName) as the router id. The frontName is used in the URL to access your controllers.
Both names have to be unique.
2. Create a controller.
Add the new file:
app/code/<VendorName>/<ModuleName>/Controller/Index/Index.php
add the following code in it:
<?php
namespace VendorName\ModuleName\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
public function execute()
{
echo 'Hello World';
exit();
}
}
All controllers have to contain a public execute method. It is called when accessing the controller.
The storefront controllers are inherited from the \Magento\Framework\App\Action\Action class.
Pay attention!
According to the Magento 2 code requirements standards, the use of the echo constructor in PHP files is prohibited, and the use of the exit constructor is totally prohibited. You may use them only temporarily for testing purposes.
In the examples, we will create a Magefan_Faq module for Frequently Asked Question (FAQ).
The resulting module structure will look like this:
├── app │ └── code │ └── Magefan // назва розробника - VendorName
│ └── Faq // назва модуля - ModuleName
│ ├── etc
│ │ ├──module.xml
│ │ └──frontend
│ │ └── routes.xm
│ │
│ ├── registration.php
│ └── Controller
│ └── Index
│ └── Index.php
│
The Magefan_Faq module files can be viewed on GitHub.
3. Clear Magento Cache. Run this CLI command:
php bin/magento cache:clean
4. Run DI (Dependency Injections). Run the CLI command:
php bin/magento setup:di:compile
5. Visit the new page.
If you want to see the newly created page, follow the link:
http://your-magento-store.com/path/index/index/
You will see the text:
Hello World
Read more to learn how to create custom block in Magento 2.