Magento 2 -Implement Magento pagination in .phtml file

Magento 2 -Implement Magento pagination in .phtml file  – by Divyanshu Rohatgi

Step 1:Create block file, and use this code-

Path– app\code\Vendor\Modulename\Block\Index


<?php

namespace [Vendor]\[Modulename]\Block\Index;
use Vendor\Modulename\Block\BaseBlock;
class [BlockFileName] extends BaseBlock
{

protected function _construct()
{
parent::_construct();
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$collection = $objectManager->create('Vendor\Modulename\Model\ResourceModel\Modulename\Collection');
$this->setCollection($collection);
}
protected function _prepareLayout()
{
parent::_prepareLayout();
/** @var \Magento\Theme\Block\Html\Pager */
$pager = $this->getLayout()->createBlock(
'Magento\Theme\Block\Html\Pager',
'simplenews.news.list.pager'
);
$pager->setLimit(5)
->setShowAmounts(false)
->setCollection($this->getCollection());
$this->setChild('pager', $pager);
$this->getCollection()->load();

return $this;
}

public function getPagerHtml()
{
return $this->getChildHtml('pager');
}

}

Step 2:Create.phtml file, and use this code-

Path– app\code\Vendor\Modulename\view\frontend\templates\index\phtnlfile.phtml

<?php
$collection = $block->getCollection();
?>
<div>............ </div>
<div class="toolbar bottom">
<?php echo $block->getPagerHtml(); ?>
</div>