0

I would like to get the html of a particular block from an external script and include it somewhere else.

In magento 1.x I would do something like this:

<?php
include_once "app/Mage.php";
umask(0);
Mage::app()->loadArea('frontend');

$layout = Mage::getSingleton('core/layout');

//load default xml layout handle and generate blocks
$layout->getUpdate()->load('default');
$layout->generateXml()->generateBlocks();

//get the loaded head and header blocks and output
$headBlock = $layout->getBlock('head');
$headerBlock = $layout->getBlock('header');
echo $headBlock->toHtml() . $headerBlock->toHtml();

https://magento.stackexchange.com/a/5080/23559

I would like to ask you, which is the correct way to achieve this with Magento 2?

Thank you!

1

This is how I managed to get the content I needed. My question is: is this an acceptable way or should I do it another way? This uses object manager directly, thing that in module's development is discouraged. May I use it in this context?

<?php

use \Magento\Framework\App\Bootstrap;
use \Magento\Store\Model\Store;
use \Magento\Store\Model\StoreManager;


require __DIR__ . '/app/bootstrap.php';
$_SERVER[StoreManager::PARAM_RUN_CODE] = 'default';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();

/* @var \Magento\Framework\App\RequestInterface $req */
$req = $obj->create("\\Magento\\Framework\\App\\RequestInterface");
$req->setParams(array('message' => 'Hello Mage 2'));

/* @var Magento\Framework\App\State $state */
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

/* @var Magento\Store\Model\StoreManagerInterface $storeManager */
$storeManager = $obj->create("\\Magento\\Store\\Model\\StoreManagerInterface");
$storeManager->setCurrentStore(1);

/* @var \Magento\Framework\View\LayoutInterface $layout */
$layout = $obj->create("\\Magento\\Framework\\View\\LayoutInterface");

/* @var \Magento\Framework\View\Element\Messages $block */
$block = $layout->createBlock('Magento\Framework\View\Element\Messages', 'messages');

/* @var  \Magento\Framework\Message\MessageInterface $message */
$message = $obj->create('Magento\Framework\Message\Error');
$message->setText($req->getParam("message")." from ". $storeManager->getStore()->getName() );

$block->addMessage($message);
echo $block->toHtml();

and the result is

<div class="messages"><div class="message message-error error"><div data-ui-id="messages-message-error" >Hello Mage 2 from Default Store View</div></div></div>

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.