Magento – Raw controller with XML layout

controllersmagento2

I have a Raw Controller where i load products in based on a search. Now i need this to be without JS and css (therefor the RAW type) because i will load that into my page later on with ajax.

This is the fastest way that i came up with to do this.

BUT , It is really hard to implement blocks and childblocks into the Raw Controller. I would prefer it much more if i could use an XML for that.

So how would i do that exactly?

Code now :

 public function execute()
    {
   $layout = $this->_template->getLayout();

        $html = '<div class="container mx-auto productsrow">';
        $html .= '<div class="row no-gutters">';
        $html .= $this->_template->setAttribute("class", 'page-products')->toHtml();
 $html .= $layout->createBlock('Vendor\Module\Block\Search\Products')->setTemplate('Vendor_Module::searchproducts.phtml')->toHtml();
        $html .= '</div>';
        $html .= '</div>';



        $this->_translateInline->processResponseBody($html);

        $result = $this->_resultRawFactory->create();
        $result->setContents($html);

        return $result;
}

As you can see i need to manually create blocks etc to have in my controller since its a raw controller.

But isn't here a way how to have a raw controller but still use an XML OR use a page controller but exclude all css/js so the page loads really fast.

Best Answer

You can to use layout handle in the custom controller (replace $handle and $blockName to your values):

/** @var \Magento\Framework\View\Result\PageFactory */
protected $pageFactory;

/**
 * @param \Magento\Framework\View\Result\PageFactory $pageFactory
 */
public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\View\Result\PageFactory $pageFactory
) {
    $this->pageFactory = $pageFactory;
    parent::__construct($context);
}

/**
 * @return \Magento\Framework\Controller\ResultInterface
 */
public function execute()
{
    /** @var \Magento\Framework\View\Result\Page $page */
    $page = $this->pageFactory->create();
    $page->addHandle($handle); // for example, wishlist_index_index

    /** @var \Magento\Framework\View\Element\AbstractBlock $block */
    $block = $page->getLayout()->getBlock($blockName); // block name in the layout

    /** @var \Magento\Framework\Controller\Result\Raw $result */
    $result = $this->resultFactory->create($this->resultFactory::TYPE_RAW);
    $result->setContents($block ? $block->toHtml() : '');

    return $result;
}

I'm not sure this approach most correct and fastest, but it is works very well on my ajax requests. Write me if you'll have any issues.

Related Topic