Load block outside Magento, and apply current template

Took me a couple minutes of debugging, but it seems relatively easy.

<?php

/*
 * Initialize magento.
 */
require_once 'app/Mage.php';
Mage::init();

/*
 * Add specific layout handles to our layout and then load them.
 */
$layout = Mage::app()->getLayout();
$layout->getUpdate()
    ->addHandle('default')
    ->addHandle('some_other_handle')
    ->load();

/*
 * Generate blocks, but XML from previously loaded layout handles must be
 * loaded first.
 */
$layout->generateXml()
       ->generateBlocks();

/* 
 * Now we can simply get any block in the usual way.
 */
$cart = $layout->getBlock('cart_sidebar')->toHtml();
echo $cart;

Please note that you must manually specify which layout handles you want to load blocks from. The ‘default’ layout handle will contain the sidebar since it is placed there from inside checkout.xml.

But using the ‘default’ layout handle can come with a significant performance cost since many modules place their blocks in this handle. You may want to put all the blocks that you use on your external site in a separate layout handle and simply load that.

The choice is yours. Good luck.

Leave a Comment