1

I created a controller which show a simple block.

public function execute() {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }

When I go to my controller page route I get the block but I get too the , and tags. So how to render a page without theses ?

I tried this :

namespace Maxime\Helloworld\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action {
    public function execute() {
        echo $this->_view->getLayout()
        ->createBlock('Maxime\Helloworld\Block\Hello')
        ->setTemplate('Maxime_Helloworld::helloworld.phtml')
        ->toHtml();
    }
}

but I get this html :

<html><head><style type="text/css"></style></head><body><h2>HelloWorld</h2>

<p>Congratulations ! You have created your first Magento Module !</p>
<p>The block classname is : Maxime\Helloworld\Block\Hello</p>
<p>Install kint with "composer require raveren/kint"</p>
<p>get the request fired by collection echo $myCollection-&gt;getSelect()-&gt;__toString();</p>
</body></html>

My block content is (I add in future some stuff here) :

<?php
namespace Maxime\Helloworld\Block;
class Hello extends \Magento\Framework\View\Element\Template {

}

My template is (it's an old module test for testing the output without html) :

<h2>HelloWorld</h2>

<p>Congratulations ! You have created your first Magento Module !</p>
<p>The block classname is : <?php echo get_class($block) ?></p>
<p>Install kint with "composer require raveren/kint"</p>
<p>get the request fired by collection echo $myCollection->getSelect()->__toString();</p>
0

If I understood your need, you can create the block directly in the controller and display it without any other html.

Update answer after update question.

You can also use the resultFactory of type RAW:

public function __construct(
//...
Magento\Framework\Controller\Result $rawResultFactory ,
//...        
)
{
    $this->rawResultFactory = $rawResultFactory;
}

and use that factory to create a raw result

public function execute(
)
{
    $html = $this->_view->getLayout()
    ->createBlock('Maxime\Helloworld\Block\Hello')
    ->setTemplate('Maxime_Helloworld::helloworld.phtml')
    ->toHtml();

    $result = $this->rawResultFactory->create();
    $result->setHeader('Content-Type', 'text/html');
    $result->setContents($html);
    return $result;
}

You can add the contents of your block in the setContents.

Reference

  • I updated my post I have also html and body tags – Kpone Mar 3 '17 at 8:51
  • 1
    The browser itself adds the tags html, head, body ... If you have a test.html file with just <h2>test</h2> and open in the browser, you will have the html, head, body rendered tags. – Rafael Ortega Bueno Mar 3 '17 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.