当前位置: 技术文章>> 如何在Magento 2中以编程方式创建小部件

文章标题:如何在Magento 2中以编程方式创建小部件
  • 文章分类: Magento
  • 16800 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


在Magento 2中以编程方式创建小部件的步骤:

步骤1:要声明自定义小部件,请在以下路径创建小部件.xml文件

app\code\Vendor\Extensionion\etc\widget.xml

现在,添加以下代码

<?xml version="1.0" ?>
<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:extention:Magento_Widget:etc/widget.xsd">
   <widget class="Vendor\Extention\Block\Customwidget" id="customwidget">
 <label>Custom Widget</label>
 <description>Creating Custom Widget</description>
 <parameters>
 <parameter name="customwidgettext" sort_order="10" visible="true" xsi:type="text">
 <label>Enter Custom text</label>
 </parameter>
 </parameters>
   </widget>
</widgets>

参数允许向小部件添加不同的字段。

第2步: 现在,在块内创建一个PHP文件。转到以下路径

app\code\Vendor\Extensionion\Block\Customwidget.php

并添加代码如下

<?php
 
namespace Vendor\Extention\Block;
 
use Magento\Framework\View\Element\Template;
use Magento\Widget\Block\BlockInterface;
 
class Customwidget extends Template implements BlockInterface
{
 protected $template = "customwidget.phtml";
}

第三步: 现在创建一个 phtml 文件,该文件将 phtml 的数据显示在前端。导航到以下路径

app\code\Vendor\Extention\view\frontend\templates\customwidget.phtml

添加以下代码

<div>
   <p>This will show the custom text field data inside widget : </p>
   <span><?php echo $block->getData(‘customwidgettext’);?></span>
</div>

结论:

通过这种方式,您可以在Magento 2中以编程方式创建小部件。


推荐文章