Create latest news block via frontend in Magento 2

Hi guys,
Today, I will continue introducing you about working with Magento 2 Frontend. We will use the Tutorial_SimpleNews module in the last post.
This is the summary after we finish this part:
- Create latest news block and use the configuration via backend to display it (Left, Right, Disable).
In order to understand this tutorial thoroughly, please review our last tutorials:
- How to create a simple module in Magento 2
- Create a module with custom database table in Magento 2
- How to use Model and Collection in Magento 2
- How to create the configuration via backend for a custom module
- Adding new menu item via backend in custom module
- Grid and Form in Magento 2 Admin Panel (Part 1)
- Grid and Form in Magento 2 Admin Panel (Part 2)
- Create the news list page via Frontend in Magento 2
- Create the news detail page via Frontend in Magento 2
Ok, now let’s get started!
We will create a block to display 5 latest posts via frontend:
Step 1: Create layout file
- Open file: app/code/Tutorial/SimpleNews/view/frontend/layout/news_news.xml (we will add 2 blocks to the page body) and insert this following code into it:
<?xml version="1.0" encoding="UTF-8"?> <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="3columns" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/ Framework/View/Layout/etc/page_configuration.xsd"> <head> <css src="Tutorial_SimpleNews::css/style.css" /> </head> <body> <referenceContainer name="sidebar.main"> <block class="Tutorial\SimpleNews\Block\Lastest\Left" name="lestest.news.left" before="-" /> </referenceContainer> <referenceContainer name="sidebar.additional"> <block class="Tutorial\SimpleNews\Block\Lastest\Right" name="lestest.news.right" before="-" /> </referenceContainer> </body> </page>
Step 2: Create block files
- Create file: app/code/Tutorial/SimpleNews/Block/Lastest.php (this file will get the news data) and insert this following code into it:
<?php namespace Tutorial\SimpleNews\Block; use Magento\Framework\View\Element\Template; use Tutorial\SimpleNews\Helper\Data; use Tutorial\SimpleNews\Model\NewsFactory; use Tutorial\SimpleNews\Model\System\Config\Status; class Lastest extends Template { /** * @var \Tutorial\SimpleNews\Helper\Data */ protected $_dataHelper; /** * @var \Tutorial\SimpleNews\Model\NewsFactory */ protected $_newsFactory; /** * @param Template\Context $context * @param Data $dataHelper * @param NewsFactory $newsFactory */ public function __construct( Template\Context $context, Data $dataHelper, NewsFactory $newsFactory ) { $this->_dataHelper = $dataHelper; $this->_newsFactory = $newsFactory; parent::__construct($context); } /** * Get five latest news * * @return \Tutorial\SimpleNews\Model\Resource\News\Collection */ public function getLatestNews() { // Get news collection $collection = $this->_newsFactory->create()->getCollection(); $collection->addFieldToFilter( 'status', ['eq' => Status::ENABLED] ); $collection->getSelect() ->order('id DESC') ->limit(5); return $collection; } }
- Create file: app/code/Tutorial/SimpleNews/Block/Lastest/Left.php (This file will check the left position and set template file) and insert this following code into it:
<?php namespace Tutorial\SimpleNews\Block\Lastest; use Tutorial\SimpleNews\Block\Lastest; use Tutorial\SimpleNews\Model\System\Config\LastestNews\Position; class Left extends Lastest { public function _construct() { $position = $this->_dataHelper->getLastestNewsBlockPosition(); // Check this position is applied or not if ($position == Position::LEFT) { $this->setTemplate('Tutorial_SimpleNews::lastest.phtml'); } } }
- Create file: app/code/Tutorial/SimpleNews/Block/Lastest/Right.php (This file will check the right position and set template file) and insert this following code into it:
<?php namespace Tutorial\SimpleNews\Block\Lastest; use Tutorial\SimpleNews\Block\Lastest; use Tutorial\SimpleNews\Model\System\Config\LastestNews\Position; class Right extends Lastest { public function _construct() { $position = $this->_dataHelper->getLastestNewsBlockPosition(); // Check this position is applied or not if ($position == Position::RIGHT) { $this->setTemplate('Tutorial_SimpleNews::lastest.phtml'); } } }
Step 3: Create template file.
- Create file: app/code/Tutorial/SimpleNews/view/frontend/templates/lastest.phtml (This file will display 5 lastest news on the page) and insert this following code into it:
<?php $latestNews = $block->getLatestNews(); if ($latestNews->getSize() > 0) : ?> <div class="block block-simplenews"> <div class="block-title"> <strong class="block-simplenews-heading"><?php echo __('Latest News') ?></strong> </div> <div class="block-content"> <?php foreach ($latestNews as $news) : ?> <div> <span>+ </span> <a href="<?php echo $this->getUrl('news/index/view', ['id' => $news->getId()]) ?>"> <span><?php echo $news->getTitle() ?></span> </a> </div> <?php endforeach; ?> </div> </div> <?php endif; ?>
Ok, it’s done. You can see your result by accessing this url: http://yourdomain.com/news
Finally, we have finished this tutorial, and I hope it’s useful for you. See you again in our next Magento 2 tutorials.
Enjoy Magento 2 challenge with MageWorld’s tutorials! Follow our facebook fanpage for further discussion.
Related Posts

Create the news detail page via frontend in Magento 2

Create the news list page via frontend in Magento 2

Grid and Form in Magento 2 Admin Panel (Part 2)
