Here the following steps help you to explain how to form widgets in Magento 2:
Step 1: Initialize widgets
Step 2: Form a widgets template
Step 3: Form a widget block
Step 4: Flush cache
Step 5: Post widgets
Initialize widgets
File directory:
app/code/Webnexs/HelloMagento/etc/widget.xml
<?xml version="1.0" ?> <widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:Hellomagento:Magento_Widget:etc/widget.xsd"> <widget class="Webnexs\HelloMagento\Block\Widget\Posts" id="Webnexs_Hellomagento_posts"> <label>New Widget</label> <description>Posts</description> <parameters> <parameter name="posts" sort_order="0" visible="true" xsi:type="text"> <label>New Widget</label> </parameter> </parameters> </widget> </widgets>
Form a widgets template
Filedirectory:
app/code/Webnexs/HelloMagento/view/frontend/templates/widget/posts.phml
<?php if($block->getData('posts')): ?> <h2 class='posts'><?php echo $block->getData('posts'); ?></h2> <p>Widget Sample</p> <?php endif; ?>
Form a widget block
File directory:
app/code/Webnexs/HelloMagento/Block/Widget/Posts.php
<?php namespace Webnexs\HelloMagento\Block\Widget; use Magento\Framework\View\Element\Template; use Magento\Widget\Block\BlockInterface; class Posts extends Template implements BlockInterface { protected $_template = "widget/posts.phtml"; }
Flush cache
Open terminal and use this command:
php bin/magento cache:flush
Post widgets
Navigate to admin panel > Content > Pages > Home page > Edit
In Content tab, tap on Insert Widget icon, you will notice the New Widget in widget list.
Leave a Reply