Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a Custom PHP Magento Block inside a template file

I've created a Custom Block based on this tutorial http://blog.magikcommerce.com/how-to-show-most-viewed-best-selling-products-in-magento-store

I would like to call the Block from my home.phtml template file.

I call my static blocks from:

<?php
$helper = Mage::helper('cms');
$source = Mage::getModel('cms/block')->load('my-block');
$processor = $helper->getPageTemplateProcessor();
$html = $processor->filter($source->getContent());
echo $html;
?>

And it works like a charm, of course! ' But how can I load dynamic blocks, in my case, inside template files.

My bestseller.phtml file is:

app/design/frontend/default/default/template/catalog/product/bestseller.phtml

And my class is:

Mage_Catalog_Block_Product_Bestseller 
like image 504
Gilberto Albino Avatar asked Sep 24 '13 15:09

Gilberto Albino


People also ask

How do I override a block template in Magento 2?

Go to vendor/magento/module-contact/view/frontend/templates from the root directory of your store and copy the form. phtml file to app/code/Magenticians/Modulecontact/view/frontend/templates. Now you just need to update the form.

How do you call one Phtml file in another Phtml file in magento2?

Re: How to call phtml file in another phtml fileecho $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magestore_Webpos::login. phtml")->toHtml();


2 Answers

Loading a block from a template file is a very bad style, but it is possible.

The dirty way from a template file

echo $this->getLayout()->createBlock('catalog/product_bestseller')->toHtml();

The clean way:
Modify the corresponding layout XML file and add the block, then refer to it with

echo $this->getChildHtml('product_bestseller');

If you want to add a block to a cms page use the Layout Xml Updates section under Design:

<reference name="content">
    <block type="catalog/product_bestseller" name="product_bestseller" />
</reference>
like image 142
Justus Krapp Avatar answered Oct 16 '22 14:10

Justus Krapp


this worked as of 1.5.1, also allows you to relocate the template

$block = $this->getLayout()
         ->createBlock('catalog/product_bestseller','product_bestseller',
                       array('template' => 'pathTo/template.phtml'));
echo $block->setBlockId('whatever')->toHtml();
like image 37
user3338098 Avatar answered Oct 16 '22 12:10

user3338098