0

I want to set template in Block custom.php. how can i do it? I tried following:

protected function _prepareLayout() {
        $this->getLayout()->createBlock('Xyaddons\Productzoom\Block\Product\View')->setTemplate('product/image.phtml')->toHtml();

        return parent::_prepareLayout();
    }

it's not running successfully.

Add new quetion

I want create funcion in custom block use to set template. it same

public function setCustomTemplate(){
    if($isActive ==="1"){
       return $this->getLayout()->getBlock('.....')->setTemplate('custom/view.phtml');
      }
}

how do it? any thank help :)

4
  • what is the error that you are getting ? the format seems correct. Try removing return from return parent::_prepareLayout(); and check Nov 3 '15 at 6:31
  • it not run file template image.phtml
    – xanka
    Nov 3 '15 at 6:39
  • I removed it not change.
    – xanka
    Nov 3 '15 at 6:50
  • You should start your question by stating at a high level what it is you wish to accomplish.
    – benmarks
    Nov 3 '15 at 12:38
4

Use $this->addChild function to add child block. Ex:

    $this->addChild(
        'back_button',
        'Magento\Backend\Block\Widget\Button',
        ['label' => __('Back'), 'template' => 'Vendor_Moduel::template.phtml' 'class' => 'cancel']
    );

Then in parent block template use $this->getChildHtml('back_button'); to render child block with template.

PS. Better to use layout to define blocks and templates

0
4

In your block file,

protected function _construct()
    {
        parent::_construct();
        $this->setTemplate('Magento_Config::page/system/config/robots/reset.phtml');
    }

check for _construct() method not confused with __construct().

You can set your Namespace_ModuleName :: path/to/template.phtml

3
  • I don't need parent consturcter, then How do I declare set template
    – Jaisa
    Jan 12 '18 at 6:16
  • you can just remove parent:construct in above function Jan 12 '18 at 6:19
  • @RakeshJesadiya, can we pass argument to the template like product id? Jan 28 '19 at 14:09

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