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:

include_once "app/Mage.php";

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

//load default xml layout handle and generate blocks

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


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

Thank you!


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?


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');

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

/* @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() );

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>
| improve this answer | |

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.