I am developing a custom module with a custom block which displays a list of products.
My Block class:
use \Magento\Framework\View\Element\Template;
class Products extends Template
{
protected $_productCollectionFactory;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
* @param array $data
*/
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 getHomeProducts()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(6);
return $collection;
}
}
.phtml file:
<?php
$productCollection = $block->getHomeProducts();
?>
<?php if($productCollection->count() > 0) : ?>
<div class="lrnt_hp_products">
<ul>
<?php foreach ($productCollection as $product) : ?>
<li>
<a href="<?php echo $product->getProductUrl(); ?>">
<img src="<?php echo $block->getUrl('pub/media/catalog') . 'product' . $product->getImage(); ?>" alt="<?php echo $product->getName(); ?>" />
</a>
<h2><a href="<?php echo $product->getProductUrl(); ?>"><?php echo $product->getName(); ?></a></h2>
// here I would like to print the price
</li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
I am trying to show product price in the phtml file but could not find proper way to show the price.
I now I can print it with:
$product->getPrice()->getPrice('final_price')->getValue()
and searching which automatically prints the final_price
, the special-price
if these are present etc.
How can I achieve this?