0

I have an plugin with after method, that should append piece of html to return.

I think that the html shoul be in some template block. Is there a way to render block from plugin?

Thanks.

2
  • which class are you use for pluginization?
    – Max
    Commented Feb 6, 2017 at 15:32
  • I'm extending \Magento\Sales\Block\Order\PrintOrder\Invoice class. (though i'm not sure, that's what are you asking for) Commented Feb 6, 2017 at 20:46

2 Answers 2

4

You can use LayoutInterface for block creating.

/**
 * @param Invoice $subject
 * @param $result
 * @return string
 */
public function afterGetItemHtml(\Magento\Sales\Block\Order\PrintOrder\Invoice $subject, $result)
{
    $renderer = $subject->getLayout()
        ->createBlock(MyCustomBlock::class);

    return $result . $renderer->toHtml();
}
1
  • Awesome, thanks! Commented Feb 7, 2017 at 9:39
0

Maybe will helpful my answer.

I added plugin for Magento\Catalog\Controller\Category\View

Will override method - execute()

Get block by name - and return in json (for my case).

public function afterExecute(\Magento\Catalog\Controller\Category\View $subject, $result)
    {
        $isAjax = $this->_request->getParam('isAjax', null);

        if (!is_null($isAjax)) {
            $block = $result->renderResult($subject->getResponse());
            $layout = $block->getLayout();

            $responseData = [];

            if ($layout->hasElement('main.content')) {
                $mainContent = $layout->renderElement('main.content');
                $responseData['main'] = $mainContent;
            }

            $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON);
            $resultJson->setData($responseData);
            return $resultJson;
        }

        return $result;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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