0

How to set custom template in custom block file. I have created a template which contains paragaraph. I need to set this template in my block file . So What is the syntax to set template. I have declared my block(frontend_model) in system.xml file, Now I need to add template in my block using setTemplate() function. Please provide me a correct solution

3
3

You can set template by call in your xml like:

<block class="Magedelight\EWallet\Block\Customer\Addmoney" name="customer_add_money" as="customer.add.money" template="Magedelight_EWallet::customer/add_money.phtml" before="-" cacheable="false"/>

OR you can call in to your phtml like:

echo $this->getLayout()
          ->createBlock('Magento\Cms\Block\Block')
          ->setBlockId('your_block_identifier')
          ->toHtml();

For another block within CMS Block in Magento 2, please use the below code to show it.

{{block class="Magento\Cms\Block\Block" block_id="your_block_identifier"}}

EDIT BY SET TEMPLATE::

$objectManager->get(\Magento\Framework\Registry::class)->register('product', $product);
        /** @var $block \Magento\Catalog\Block\Product\ProductList\Crosssell */
        $block = $objectManager->get(\Magento\Framework\View\LayoutInterface::class)
            ->createBlock(\Magento\Catalog\Block\Product\ProductList\Crosssell::class);
        $block->setLayout($objectManager->get(\Magento\Framework\View\LayoutInterface::class));
        $block->setTemplate('Magento_Catalog::product/list/items.phtml');
        $block->setType('crosssell');
        $block->setItemCount(1);
        $html = $block->toHtml();

OR in you can write in your block

protected function _prepareLayout()
    {
        parent::_prepareLayout();
        $this->setTemplate('Vendor_module::list/product.phtml');
        return $this;
    }
2
  • I don't want to use layout to set template – Jaisa Jan 12 '18 at 7:09
  • I have declared my block in system.xml file, Now I need to add template in my block using setTemplate() – Jaisa Jan 12 '18 at 7:10

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