Hi. To be honest, I just started to investigate Magento 2 and it’s structure these days.

As a starting point, I decided to follow this great article by Ash Smith about Creating Simple Magento 2 Controller Module.

And everything was just fine until the moment I needed to render the view from my newly created controller like in above post.

In fact, everything still worked fine, just one thing was not right:

rendering page1

My PhpStorm said that ‘_view’ variable is marked as deprecated.

So, I can accept to continue using this approach, or I could investigate a little bit more to find out new ways of rendering the view from inside controller. It is obvious that there is a newer approach which should be used instead.

First, let’s create new controller action, let’s call it Page:

rendering page2

namespace Apiworks\HelloWorld\Controller\Index;
class Page extends \Magento\Framework\App\Action\Action
    public function execute()

Instead of using ‘_view’ variable which became deprecated, we first need to override controller class constructor to be able to inject ‘PageFactory’ object instance which will be used in execute action.

_resultPageFactory = $resultPageFactory;
    public function execute()

Next, we need to add execute method where we are creating our view and returning it as result:

        return $result;

After visiting URL: http://magento2url/helloworld/index/
page , we should see main Magento page / view rendered in our browser.

rendering page3

Let’s add our custom “HelloWorld” block inside content to display the message “Hello World”.
In order to do that, we need to add layout XML file for our layout route/handle.

Navigate inside app/code/{yourpackage}/{yourmodule}/view/frontend/layout/ and create file: helloworld_index_page.xml which reflects our layout handle which is constructed from: {frontName as defined in etc/frontend/routes}_{controller name}_{action_name}

rendering page4

And add this content inside:

<?xml version=“1.0”?>
<page xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xsi:noNamespaceSchemaLocation=“../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd”>
      <referenceContainer name=“content”>
          <block class=“Apiworks\Helloworld\Block\Helloworld” name=“helloworld” template=“helloworld.phtml”/>

Of course, we need to add our Block: “HelloWorld.php” and Template: “helloworld.phtml” and we are done. The content of our block is now displayed inside Magento’s content container.