Шаблонизация модулей
рейтинг: 8.6/10, голосов: 17
Правильная шаблонизация любой части сайта - это простота разработки и удобство управления сайтом в будущем. Этот вопросы и еще некоторые мелочи (например, создание ссылок на материалы) мы разберем на примере создания модуля, который будет выводить случайный список последних материалов.
Разделение кода модуля
Все что мы делали до этого в предыдущих статьях по написанию модулей - это каша из кода. В одном файле разом происходят: запрос к базе данных, преобразование данных, логика модуля, подстановка полученной информации в html-код. Если сейчас вам кажется что код маленький и простой, то продолжая в таком духе это все превратится в кашу. Особенно много сложностей возникнет, когда вы после небольшого перерыва решите что-нибудь изменить.
Для внутреннего упрощения модуля, попробуем разделить его код на некоторые логические части, а именно - шаблон и helper. Шаблон будет отвечать за верстку, html-код. Helper - это класс помощник, который будет содержать в себе выборку из базы данных и форматирование данных так, чтобы их только осталось вставить в html.
Теперь PHP-файл выглядит следующим образом:
<?php
defined('_JEXEC') or die('Restricted access');
// Подключаем локальный helper
require_once(dirname(__FILE__).DS.'helper.php');
// Вызываем метод
$link = modRandomLatestHelper::getList($params);
// подключаем файл шаблона с помощью класса JModuleHelper
require(JModuleHelper::getLayoutPath('mod_ranlatest'));
?>
А фaйл helper.php будет выглядеть так:
<?php
defined('_JEXEC') or die('Restricted access');
// Используем route.php для создания ссылок на контент
require_once (JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');
class modRandomLatestHelper
{
function getList(&$params)
{
// Получаем значение параметров
$psecid = trim($params->get("secid"));
$panum = (int) trim($params->get("articlenum"));
$pfront = $params->get("front", 0);
$pptext = trim($params->get("pretext"));
$mcsuffix = trim($params->get("stylesfx"));
// Получаем глобальный объект базы данных
$db =& JFactory::getDBO();
// Собираем sql-запрос
if ($psecid)
{
$arrsecid = explode(",", $psecid);
JArrayHelper::toInteger($arrsecid);
$CondA = " AND (sectionid = " . implode(' OR sectionid = ', $arrsecid ) . ")";
}
if (!$pfront) $CondB = " AND id NOT IN (select content_id from #__content_frontpage)";
if ($panum) $Lim = "LIMIT 0, $panum";
$query = "SELECT id, catid, sectionid, title FROM #__content WHERE state=1" .
($psecid ? $CondA : '') . ($pfront ? '' : $CondB) .
" ORDER BY created ASC $Lim";
// Выполняем запрос и получаем массив объектов
$db->setQuery($query);
$rows = $db->loadObjectList();
if (!$db->getErrorNum())
{
if (!empty($rows))
{
$ranitem = rand(0,count($rows)-1);
$link = array();
$link[0] = $pptext;
$link[1] = $rows[$ranitem]->title;
// Создаем ссылку на контент с помощью ранее подключенного роутера (route.php)
$link[2] = ContentHelperRoute::getArticleRoute($rows[$ranitem]->id,
}
}
// Возвращаем массив ссылок и заголовков
return $link;
}
}
?>
Шаблон, который подключается с помощью getLayoutPath - обычно должен располагаться по адресу /tmpl/default.php, либо переопределяется из соотвествующей директории в основном шаблоне сайта. (в нашем случаем его переопределит файл /templates/YOU_TEMPLATE/html/mod_MODULENAME/default.php ). Таким образом, если организовывать файлы так, как описано выше, то мы получим очень удобную и гибкую систему шаблонов для модуля.
Посмотрим на содержимое файла default.php:
<?php if ($link[0]) : ?>
<p class="ranlatest<?php echo $params->get('stylesfx'); ?>">
<?php print $link[0] ?>
</p>
<?php endif; ?>
<a class="ranlatest<?php echo $params->get('stylesfx'); ?>"
href="/<?php print $link[2] ?>"><?php print $link[1] ?></a>
Несколько шаблонов в одном модуле
Добавим несколько строк в xml файл модуля Joomla:
<param name="layout" type="list" default="random"
label="Layout"
description="The layout to display the link">
<option value="default">Default</option>
<option value="divmania">Div-mania</option>
<option value="oldschool">Old-school</option>
</param>
В основном PHP-файле (mod_ranlatest.php) изменим последнюю строку на следующую :
$layout = $params->get('layout', 'default');
require(JModuleHelper::getLayoutPath('mod_ranlatest', $layout));
Добавим в папку шаблонов (/modules/mod_ranlatest/tmpl/) соответствующие файлы:
файл divmania.php - верстка с использованием div'ов
<div class="ranlatest<?php echo $params->get('stylesfx'); ?>">
<?php if ($link[0]) : ?>
<p><?php print $link[0] ?></p>
<?php endif; ?>
<a href="/<?php print $link[2] ?>"><?php print $link[1] ?></a>
</div>
и файл oldschool.php - вариант табличной верстки
<table class="ranlatest<?php echo $params->get('stylesfx'); ?>">
<?php if ($link[0]) : ?>
<tr><td>
<?php print $link[0] ?>
</td></tr>
<?php endif; ?>
<tr><td>
<a href="/<?php print $link[2] ?>"><?php print $link[1] ?></a>
</td></tr>
</table>
HELPER.PHP: 48 строка...
// Создаем ссылку на контент с помощью ранее подключенного роутера (route.php)
$link[2] = ContentHelperRoute::getArticleRoute($rows[$ranitem]->id,
}
}
ContentHelperRoute::getArticleRoute($rows[$ranitem]->id,.........
В Joomla 1.7 пришлось заменить эту 48 строчку на такую
$link[2] = JRoute::_(ContentHelperRoute::getArticleRoute($rows[$ranitem]->id));
а в default.php убрать /
href="/<?php print $link[2] ?>"><?php print $link[1] ?></a>
Я не силен в написании модулей и вообще любых кодов, но есть некая задумка... Есть модуль вывода новостей RSS. Хочу вывести новости в бегущей строке с ссылкой на источник. Возможно ли изменить этот модуль для отображения именно в бегущей строке? Или искать уже готовый модуль? Задавал этот вопрос не нескольких форумах, но ответа нет. Что посоветуете?
Et sur ce le noble olivier remply d'un noble
couraige et d'un vouloir ardant a complaire ouyez les nouvelles de son lict se leva
et commenca a estandre ses bras et a sentir s'il seroit
possible a luy de porter armes.
It's nearly impossible to find experienced people about this
subject, but you seem like you know what you're talking about!
Thanks
I believe that is one of the most vital information for me.
And i amm happy reading yyour article. However wanna
remark on few general things, The website taste is wonderful, the articles is actually grdat :
D. Good activity, cheers
These reviews have ranged from people that just park
their cars in the garage to those that rebuild tractors in their large shop.
Ahaa, its nice conversation on the topic of this paragraph at this place at this web
site, I have read all that, so now me also commenting
at this place.
Hello my family member! I want to say that this article is
amazing, nice written and come with approximately
all vital infos. I'd like to see extra posts like this .
At this mokent I am going too doo my breakfast,
when having my breakfast coming yet again to read further news.
Thanks for this rattling ?ost, I am glad I detected this site on yahoo.
You ma?e some clear points there. I looked on the internet for
the issue and found most guyѕ wіll consent with your ?ebsite.
Depending up?n tthe nature of application, there exіst a wide range of heaters and ocens that not оnly make
your task easier but alsso are safe and green to use.
Record, a spherical a sіngle, but most work may bе fixed with high ?uality sandpap?r.
Appliances receive water from the cylinder shaped tank through the pipе
networ? and watrr valve s?stem attached to the ?ater heater after the water has been heated.
Red elicits fеelings оf speеd, excitement, strength, energy, and passion. HP Primter Service grants constant repairing service and conservation to alll industries th?t possess and activates larhe
format printers (pl?tters). Most remanufacturers you will save
between 25% and 50% off new OEM prices.
Wit? knitting being a favorite passion in many different
internatoonal locations around t?e world, there is a signifigant amount of shops
all pro?iding various thicknesѕes of knitting yarn, іn a?dition too a wise variety ?f
knitting add-ons that aree claimmed to be more or less neceѕsary for varіouѕ pгojects.
One oof the initial extras that wil? become cru?ial fоr yourself as a knitter is the
knitting bag. This particular accessor? will
not onlpy supply you with tthe best method to hold your
incomplete projects, your yarn along with youг knitting needles, but
it'll also let yоu carгy yo?r materials on hand without h?ving to worry that
they're g?ing to end up compromised.
Thhе рackages offer different levels of servicе, all c?swtom ?esigned to cast an efffect
on the website in their own way. Professional SEO services always
give detailеd reports on theikr work and the results achieved by the strategy.
Professіonalіzed experts and member oof friends?ip helps a?t every step aand providig creative and effective solutions to build ?our site
online.
Excellent post. Keep posting ѕuch kind of infvo on youur site.
Im reallyy imppressed by your site.
Hey there, You'veperformed an еxcellеnt job. I will certainly digg it and
personally suggest to my friends. I'm sure they'll be benefited from this web site.
?iуa! Quick question th?t's entirely off topic.
Do you know ?ow to make your site moЬile friеndly?
M? sіte loks ?eird when browsing frim my
ip?one4. ?'m trying to find a theme or plugin th?at mіght bee
aЬle to res?lve thiѕ problem. If yoоu have any гecommendations,
please share. Thank you!
{
W?at's up, Steve with Brid??s.
Really “Шаблонизация модулей / Создание модулей Joomla .:.
Документация Joomla! CMS” is indeed an original topic
I just wanted to s?are that I lioke y?ur ??st.
I rea? this piece of writing fully regarding the difference of most гeсent and? preceding technologies,
it's remarkable artic?e.
?hat being said, HS 200 Series produ?ts have bеen known to function betteг
than comparablе sеalers in situations where a single-coat exterior acrylic se??er
is requіred.
A m?tivating disc?sѕion is worrth comment.
T?ere's no doubt that that you ought to write more on thiѕ subject matter, it may
not be a taboo subject butt usually folks don't discuss
such subjects. T? the next! Cheers!!
Howdy would you mind sharing which blog platform you're using?
I'm looking to start my own blog in the near future but I'm
having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your layout seems different then most blogs and I'm
looking for something unique. P.S Apologies
for being off-topic but I had to ask! https://kasino.vin/home/3win81/54-3win8-mobile-slot