Как создать свой виджет
Widgetkit - это модульный и расширяемый в дизайне компонент: контент виджета и его отображение отделены друг от друга. В этой статье вы узнаете, как создать свой виджет в Widgetkit 2. Виджет используется компонентом для определения того, как выбранный элемент контента будет отображаться на сайте. Это дает возможность использовать элемент контента в нескольких вариантах виджетов с различными вариантами отображения.
Для начала, чтобы создать свой виджет, вы можете скопировать один из существующих и начать адаптировать его под свои нужды. В альтернативе, вы можете создать абсолютно новый, следуя шагам, указанным в статье.
В обоих случаях вы должны ссылаться на существующие плагины, как ссылки. Они расположены в папках
In both scenarios you shoud rely on the existing plugins as reference. They are located in the
СОВЕТ: Убедитесь, что вы расположили ваши настройки в таком месте, в котором они не будут перезаписаны в процессе обновления Warp Framework.
<?php return array( // Main class the plugin is extending
'main' => 'YOOtheme\\Widgetkit\\Widget\\Widget', // Plugin configuration
'config' => function($app) { return array( // Plugin raw name
'name' => 'PLUGIN-NAME', // Plugin label which will be displayed to the user
'label' => 'PLUGIN-LABEL', // Url to the icon that will be used in the widget plugin overview
'icon' => $app['url']->to('plugins/widgets/PLUGIN-NAME/widget.svg'), // Path to the view file that will be used when rendering the widget
'view' => 'plugins/widgets/PLUGIN-NAME/views/widget.php', // Supported widget fields
// A list of fields the widget requires from a selected content element.
// Example: The map requires a 'location' field to be present.
'item' => array('title', 'content'), // Default settings to be used for every widget instance
'settings' => array(
'key' => 'value'
)
);
},
// An array of Widgetkit events you want to listen to
'events' => array(
// Triggered when Widgetkit is initialized in the back end
'init.admin' => function($event, $app) {
// Registers the edit view
$app['angular']->addTemplate('PLUGIN-NAME.edit', 'plugins/widgets/PLUGIN-NAME/views/edit.php', true);
},
// Triggered when Widgetkit is initialized in the front end
'init.site' => function($event, $app) {},
// Triggered when Widgetkit is initialized
'init' => function($event, $app) {}
) );
Лучший вариант, чтобы понять возможности отображения, это изучение кода в предустановленных виджетах.
Чтобы начать, далее приведены ссылки доступных значений внутри файла
СОВЕТ: когда вы проводите цикл через переменную
В обоих случаях вы должны ссылаться на существующие плагины, как ссылки. Они расположены в папках
In both scenarios you shoud rely on the existing plugins as reference. They are located in the
/wp-content/plugins/widgetkit/plugins/widgets
WordPress и /administrator/components/com_widgetkit/plugins/widgets
Joomla. СОВЕТ: Убедитесь, что вы расположили ваши настройки в таком месте, в котором они не будут перезаписаны в процессе обновления Warp Framework.
Структура файла
|-- plugin.php // main plugin content
|-- widget.svg // plugin icon in SVG format
+-- views/
| edit.php // edit form layout
| widget.php // widget form layout
plugin.php
Файлplugin.php
содержит массив PHP для настройки вашего плагина для получения конфигурации и функций событий Widgetkit. Не забывайтео о состоянии return
, так как этот файл настроен нп возвращение правильного массива конфигурации.<?php return array( // Main class the plugin is extending
'main' => 'YOOtheme\\Widgetkit\\Widget\\Widget', // Plugin configuration
'config' => function($app) { return array( // Plugin raw name
'name' => 'PLUGIN-NAME', // Plugin label which will be displayed to the user
'label' => 'PLUGIN-LABEL', // Url to the icon that will be used in the widget plugin overview
'icon' => $app['url']->to('plugins/widgets/PLUGIN-NAME/widget.svg'), // Path to the view file that will be used when rendering the widget
'view' => 'plugins/widgets/PLUGIN-NAME/views/widget.php', // Supported widget fields
// A list of fields the widget requires from a selected content element.
// Example: The map requires a 'location' field to be present.
'item' => array('title', 'content'), // Default settings to be used for every widget instance
'settings' => array(
'key' => 'value'
)
);
},
// An array of Widgetkit events you want to listen to
'events' => array(
// Triggered when Widgetkit is initialized in the back end
'init.admin' => function($event, $app) {
// Registers the edit view
$app['angular']->addTemplate('PLUGIN-NAME.edit', 'plugins/widgets/PLUGIN-NAME/views/edit.php', true);
},
// Triggered when Widgetkit is initialized in the front end
'init.site' => function($event, $app) {},
// Triggered when Widgetkit is initialized
'init' => function($event, $app) {}
) );
views/edit.php
Файлview/edit.php
содержит макет формы, которая отображается, когда вы настраиваете опции отображения виджета.Он связан с UIkit для его стилизации и с AngularJS для логики его работы. Вы можете изучить соответствующую документацию.
<!-- wrap the content with uk-form and uk-grid styles -->
<div class="uk-grid uk-grid-divider uk-form uk-form-horizontal" data-uk-grid-margin>
<!-- set the left column -->
<div class="uk-width-medium-1-4">
<!-- set the wk specific style -->
<div class="wk-panel-marginless">
<!-- set the navigation connecting it to the uk-switcher -->
<ul class="uk-nav uk-nav-side" data-uk-switcher="{connect:'#nav-content'}">
<li><a href="/">General</a></li>
<li></li>
<!-- keep adding them as you need -->
</ul>
</div>
</div>
<!-- set the right column -->
<div class="uk-width-medium-3-4">
<!-- set the uk-switcher content -->
<ul id="nav-content" class="uk-switcher">
<!-- general switcher section content -->
<li>
<div class="uk-form-row">
<label class="uk-form-FIELD-NAME" for="wk-columns">FIELD-LABEL</label>
<div class="uk-form-controls">
<select id="wk-FIELD-NAME" class="uk-form-width-medium" ng-model="widget.data['FIELD-NAME']">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
</div>
</li>
<li></li>
<!-- keep adding one for each section you have set -->
</ul>
</div>
</div>
views/widget.php
Этот файл используется для отображения виджета на сайте. Контент и настройки отображения комбинируются и конвертируются в код html для вашего браузера.Лучший вариант, чтобы понять возможности отображения, это изучение кода в предустановленных виджетах.
Чтобы начать, далее приведены ссылки доступных значений внутри файла
views/widget.php
.
Переменная | Описание |
---|---|
$settings | Массив настроек отображения |
$items | Массив элементов контента, которые будут отображены. Они сопровождаются провайдером контента. |
$items, вы можете получить доступ к собственным полям по их ключам.Доступные ключи определены в конфигурации
item провайдера контента
, например: $item['customkey']
.