0

First, I am new to Magento 2. My aim is to achieve when products added in the backend I want it to show in my custom template.

Can anyone suggest some methods to do it?

1 Answer 1

1

You need to create a custom module for this and create a custom block in app\code\Vendor\Module\Block\Product.php

<?php
namespace Vendor\Module\Block;
class Product extends \Magento\Framework\View\Element\Template
{    
    protected $_productCollectionFactory;

    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    )
    {    
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
    }

    public function getProductCollection()
    {
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        return $collection;
    }
}

And create your custom template in app\code\Vendor\Module\view\frontend\templates\your_template.php

$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
    print_r($product->getData());     
    echo "<br>";
}

Call your custom template in any xml

<referenceContainer name="content">
    <block class="Vendor\Module\Block\Product" name="custom.block" template="Vendor_Module:: your_template.phtml"/>
</referenceContainer>

Or you can call your template in cms pages using

{{block class="Vendor\Module\Block\Product" template="Vendor_Module:: your_template.phtml"}} 
4
  • where I have to call the template in which XML file
    – jithin
    Jan 23, 2020 at 11:29
  • Where do you want to display the template? Jan 23, 2020 at 11:29
  • like if I want to display in product page
    – jithin
    Jan 23, 2020 at 11:33
  • create a file in app\code\Vendor\Module\view\frontend\layout\catalog_product_view.xml each page will have some separate xml file name..You can see those in like vendor\magento\module-catalog\view\frontend\layout Jan 23, 2020 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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