Создание шаблона
Руководство по созданию макета (болванки) для шаблона
рейтинг: 9.5/10, голосов: 51
Для начала необходима обычная XHTML страничка. Можно воспользоваться каким-нибудь сервисом для генератора HTML шаблонов. Или создать шаблон самостоятельно. Рассмотрим, в качестве примера, часто используемый шаблон с шапкой, футером и двумя колонками по бокам.

Разметка HTML будет выглядеть так:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<meta name="title" content="" />
<meta name="keywords" content="" />
<meta name="description" content="" />
<link rel="stylesheet" href="/style.css" type="text/css" media="screen, projection" />
<!--[if lte IE 6]><link rel="stylesheet" href="/style_ie.css" type="text/css" media="screen, projection" /><![endif]-->
</head>
<body>
<div id="wrapper">
<!-- #header-->
<div id="header">
</div>
<div id="middle">
<div id="container">
<div id="content">
</div><!-- #content-->
</div><!-- #container-->
<div class="sidebar" id="sideLeft">
</div><!-- .sidebar#sideLeft -->
<div class="sidebar" id="sideRight">
</div><!-- .sidebar#sideRight -->
</div><!-- #middle-->
<div id="footer">
</div><!-- #footer -->
</div><!-- #wrapper -->
</body>
</html>
И файл стилей style.css, для данной разметки:
* {
margin: 0;
padding: 0;
}
body {
font: 12px/18px Arial, Tahoma, Verdana, sans-serif;
}
a {
color: blue;
outline: none;
text-decoration: underline;
}
a:hover {
text-decoration: none;
}
/* Begin of styles for the demonstration (you can remove them) */
a.expand {
width: 150px;
display: block;
margin: 10px 0 0;
}
a.expand:hover {
height: 500px;
}
/* End of of styles for the demonstration */
p {
margin: 0 0 18px
}
img {
border: none;
}
input {
vertical-align: middle;
}
#wrapper {
width: 100%;
min-width: 1000px;
}
/* Header
---------------------------------------*/
#header {
height: 150px;
background: #FFE680;
}
/* Middle
---------------------------------------*/
#middle {
border-left: 250px solid #B5E3FF;
border-right: 250px solid #FFACAA;
height: 1%;
position: relative;
}
#middle:after {
content: '.';
display: block;
clear: both;
visibility: hidden;
height: 0;
}
#container {
width: 100%;
float: left;
overflow: hidden;
margin-right: -100%;
}
#content {
padding: 0 20px;
}
/* Sidebar Left
---------------------------------------*/
#sideLeft {
float: left;
width: 250px;
position: relative;
background: #B5E3FF;
left: -250px;
}
/* Sidebar Right
---------------------------------------*/
#sideRight {
float: right;
margin-right: -250px;
width: 250px;
position: relative;
background: #FFACAA;
}
/* Footer
---------------------------------------*/
#footer {
height: 100px;
background: #BFF08E;
}
Обзор макета для Joomla
С точки зрения Joomla этот макет разбивается на области, где будет выводиться основное содержимое (компонент) и дополнительное (модули).

При создании шаблонов Joomla используются следующие конструкции для вывода содержимого:
Содержимое HEAD
Здесь выводятся содержимое между тегами <head>…</head>, мета описание, заголовок страницы, подключаемые JavaScript и т. д. Для этого используется конструкция:
<jdoc:include type="head" />
Основное содержимое (компонент)
Для вывода основного содержимого, как правило это является содержимое компонента, используется следующая конструкция:
<jdoc:include type="component" />
Содержимое сообщения
Для вывода системных сообщений, например, сообщение при неудачной авторизации, используется конструкция:
<jdoc:include type="message" />
Содержимое модулей
Для вывода содержимого модулей используется конструкция:
<jdoc:include type="modules" name="position" style="xhtml" />
Для контроля и подсчета модулей в позициях предусмотрен метод countModules.
Содержимое модуля
Можно также вывести содержимое одного модуля, для этого используется конструкция:
<jdoc:include type="module" name="custom" title="Title for module" />
- name — это название модуля, в данном примере это будет mod_custom
- title — заголовок модуля, должен совпадать с настройками модуля
В эту конструкцию можно добавлять дополнительные атрибуты, для контроля вывода содержимого модуля, например style=«xhtml».
При добавлении позиций или модуля в шаблон, не забывайте проверять настройки модулей — публикацию модуля и доступность модуля для текущего пользователя.
Использование параметров в шаблоне
Параметры для шаблона устанавливаются в XML файле описания шаблона. Их можно устанавливать в административной панели Joomla для нужного шаблона («Расширения» -> «Менеджер шаблонов»). С помощью этих параметров можно контролировать поведение шаблона, например, задать какой-то цвет для фона, вывести в качестве логотипа нужную картинку и т. п. Для получения значения параметра в шаблоне используется:
<?php $this->params->get('Имя параметра'); ?>
Соответственно для вывода значение параметра используется:
<?php echo $this->params->get('Имя параметра'); ?>
Стандартно в Joomla используется несколько типов для параметров, которые описываются в XML файле.
Шаблон для Joomla
С учетом этих данных нужно переписать HTML шаблон, сделать его шаблоном для Joomla. Расставить позиции модулей по своим местам, создать и подключить нужные CSS стили, задать область для вывода компонента и сообщений.
<?php
// защита от прямого доступа к файлу
defined('_JEXEC') or die;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>" >
<head>
<jdoc:include type="head" />
<link rel="stylesheet" href="/<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/css/style.css" type="text/css" />
<!--[if lte IE 6]>
<link rel="stylesheet" href="/<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/css/style_ie.css" type="text/css" />
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- #header-->
<div id="header">
<?php if ($this->params->get('logo')) : ?>
<img src="/<?php echo $this->baseurl ?>/<?php echo htmlspecialchars($this->params->get('logo')); ?>" alt="MyLogo" />
<?php endif;?>
<jdoc:include type="modules" name="top" style="xhtml" />
</div>
<div id="middle">
<div id="container">
<div id="content">
<jdoc:include type="message" />
<jdoc:include type="component" />
</div><!-- #content-->
</div><!-- #container-->
<div class="sidebar" id="sideLeft">
<jdoc:include type="modules" name="left" style="xhtml" />
</div><!-- .sidebar#sideLeft -->
<div class="sidebar" id="sideRight">
<jdoc:include type="modules" name="right" style="xhtml" />
</div><!-- .sidebar#sideRight -->
</div><!-- #middle-->
<div id="footer">
<jdoc:include type="modules" name="footer" style="xhtml" />
</div><!-- #footer -->
</div><!-- #wrapper -->
</body>
</html>
Нужно сохранить этот файл как index.php, это будет основной файл шаблона. В этом примере используется один параметр с именем «logo», в зависимости от которого будет выводиться соответствующая картинка в шапке шаблона. Хотя этих параметров может быть сколько угодно много и разного типа. Свойства типа $this->baseurl и т. п., это стандартные свойства Joomla, которые берутся из классов JDocumentHTML и JDocument соответственно.
XML файл инструкций для шаблона
Теперь нужно создать XML файл инструкций для шаблона templateDetails.xml
<?xml version="1.0" encoding="utf-8"?>
<extension version="1.6" type="template" client="site">
<!-- Название шаблона -->
<name>Mytemplate</name>
<!-- Это не обязательные элементы, отображают информацию о авторе, лицензии и прочее -->
<creationDate>21 May 2010</creationDate>
<author>SmokerMan</author>
<authorEmail>j-wiki@bk.ru</authorEmail>
<authorUrl>http://www.j-wiki.ru</authorUrl>
<copyright>Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.</copyright>
<license>GNU General Public License version 2 or later</license>
<!-- Версия шаблона -->
<version>1.6.0</version>
<!-- Описание шаблона -->
<description>TPL_MYTEMPLATE_XML_DESCRIPTION</description>
<!-- Файлы из которых состоит шаблон -->
<files>
<!-- Можно указывать директории -->
<folder>css</folder>
<folder>language</folder>
<filename>index.html</filename>
<filename>index.php</filename>
<filename>templateDetails.xml</filename>
</files>
<!-- Позиции модулей, используемые в шаблоне -->
<positions>
<position>top</position>
<position>left</position>
<position>right</position>
<position>footer</position>
</positions>
<!-- Установка/Удаление файлов локализации -->
<languages folder="language">
<language tag="ru-RU">ru-RU/ru-RU.tpl_mytemplate.ini</language>
<language tag="ru-RU">ru-RU/ru-RU.tpl_mytemplate.sys.ini</language>
</languages>
<!-- Параметры для шаблона -->
<config>
<fields name="params">
<fieldset name="advanced">
<field name="logo" type="media"
label="TPL_MYTEMPLATE_LOGO_LABEL"
description="TPL_MYTEMPLATE_FIELD_LOGO_DESC" />
</fieldset>
</fields>
</config>
</extension>
Локализация шаблона
Для перевода значений используются файлы локализации. Нужно создать их в директории language. Например, файл для перевода описаний и позиций для русской локализации будет следующий:
language/ru-RU/ru-RU.tpl_mytemplate.sys.ini.
TPL_MYTEMPLATE_XML_DESCRIPTION="Это мой первый шаблон"
TPL_MYTEMPLATE_POSITION_TOP="Модули вверху"
TPL_MYTEMPLATE_POSITION_LEFT="Модули слева"
TPL_MYTEMPLATE_POSITION_RIGHT="Модули справа"
TPL_MYTEMPLATE_POSITION_FOOTER="Модули внизу"
В этой директории нужно создать второй файл, для перевода значений параметров, ru-RU.tpl_mytemplate.ini.
TPL_MYTEMPLATE_LOGO_LABEL="Логотип"
TPL_MYTEMPLATE_FIELD_LOGO_DESC="Выберите желаемый логотип"
Конечная структура шаблона
Также в каждой директории желательно создать пустые файлы index.html, для запрета листинга директорий.
<html><body bgcolor="#FFFFFF"></body></html>
Структура файлов обычного шаблона для Joomla будет следующей:

Теперь можно архивировать файлы в ZIP архив и устанавливать в Joomla через «Менеджер расширений».
Внизу можете загрузить готовый архив с созданным шаблоном.
Не знаю, насколько это важно для Вас.
Вот ошибка в ссылке в шаблоне:
<link rel="stylesheet" href="/
Правый слеш надо убрать!
С Уважением!
Не думаю что слэш убирать нужно. Если файл ищется от корня сайта то слэш необходим....
Именно так! Первый слеш лишний!
Ошибка! Не найден XML-файл установки Joomla!
Файл XML есть!
Роман, возможно вы сохранили файл не в той кодировке, например в блокноте кодировка по умолчанию ANSI, а нужно в Юникоде, у меня такое было.
Роман, проверьте сам файл, может скобки не закрыты
Совершенно ничего толком и по делу, бред для дураков
Еще одна ошибка в файле шаблона.
Вот строки кода (ОБРАТИТЕ ВНИМАНИЕ на href="/s<?php и потерянную букву в tyle_ie.css):
<!--[if lte IE 6]>
<link rel="stylesheet" href="/s<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/css/tyle_ie.css" type="text/css" />
<![endif]-->
Правильный вариант:
<!--[if lte IE 6]>
<link rel="stylesheet href="/<?php echo $this->baseurl; ?>/templates/<?php echo $this->template; ?>/css/style_ie.css" type="text/css" />
<![endif]-->
А по-моему, нормальное описание, мне пригодилось.
Сайту респект!
Спасибо, по вашей статье сделал наш сайт стоматологии без помощи программистов.
На счет того, что не хочет устанавливатся шаблон то причина в том, что вместо тега в templateDetails.xml
<extension version="1.6" type="template" client="site">
используйте
<install version="1.6" type="template">
по крайней мере мне помогло)
И еще такой вопрос:
У меню с всего шаблона отображается только header. Тоесть видно желтый фон. В чем причина?
Что то мне подсказывает что причина в етом куске кода:
<?php if ($this->params->get('logo')) : ?>
<img src="/<?php echo $this->baseurl ?>/<?php echo htmlspecialchars($this->params->get('logo')); ?>" alt="MyLogo" />
<?php endif;?>
<jdoc:include type="modules" name="top" style="xhtml" />
У меня получилось только после того, как я добавила доктайп из стандартного файла и удалила комментарии
справка ип на визу словакия
My spouse and I absolutely love your blog and find the majority of your
post's to be just what I'm looking for. Does one offer guest writers to write
content available for you? I wouldn't mind creating a post or elaborating on a few of the subjects you write about here.
Again, awesome web log!
оформление швейцарской визы в екатеринбурге
Greetings from Florida! I'm bored to tears at work so
I decided to browse your blog on my iphone during lunch break.
I really like the information you provide here and can't wait to take
a look wwhen I get home. I'm surprised at how quick your blog loaded on my phone ..
I'm not even using WIFI, just 3G .. Anyways, great site!
You'll additionally desire to be sure that anyone retain your money well-hidden on oneself.
Pretty nice post. I just stumbled upon your weblog
and wished to mention that I've truly loved surfing around your weblog posts.
After all I'll be subscribing on your rss feed and I am hoping
you write once more soon!
Ahaa, its fastidious dialogue about this piece of writing here
at this weblog, I have read all that, so at this time me also commenting here.
Good post. I learn something new and challenging on websites
I stumbleupon everyday. It will always be useful to read through articles from
other authors and use something from their websites.
What's up colleagues, its enormous piece of writing regarding teachingand fully explained,
keep it up all the time.
Hi there colleagues, how is the whole thing, and what you
would like to say regarding this article, in my view its actually awesome designed for
me.
At this time it looks like BlogEngine is the best blogging
platform available right now. (from what I've read) Is that what you are using on your blog?
Great article, totally what I needed.
Wow! After all I got a web site from where I can actually get valuable information concerning my study and knowledge.
Do you mind if I quote a few of your posts as long as I provide credit and sources back to your website?
My blog is in the very same area of interest as yours and my visitors would
truly benefit from some of the information you provide here.
Please let me know if this ok with you. Many thanks!
If you want to improve your familiarity simply keep visiting this
web page and be updated with the hottest news posted here.
Hello to all, since I am actually eager of reading this website's post to be updated on a
regular basis. It carries pleasant material.
Hey there! I simply wish to offer you a big thumbs up for your excellent info you've
got right here on this post. I am returning to your website for more soon.
Great work! This is the kind of information that should be shared around the internet.
Shame on the seek engines for not positioning this put up higher!
Come on over and visit my web site . Thank you =)
bunadisisj nsjjsjsisjsmizjzjjzjzz zumzsert
bunadisisj nsjjsjsisjsmizjzjjzjzz zumzsert
After i originally commented I appear to get clicked the -Notify me when new feedback are extra- checkbox and Any further every time a remark is additional I recieve four emails with the exact same remark. Is there a means you can easily take out me from that services? Quite a few thanks!
This great site was… how do you say it? Related!! Eventually I’ve identified something which helped me. Numerous many thanks!
Place on with this produce-up, I absolutely believe this site desires a terrific deal more focus. I’ll probably be returning to examine extra, many thanks for the data!
Spot on with this particular publish-up, I actually believe that this website needs far more attention. I?ll possibly be again once more to browse a lot more, many thanks for the information!
Hi joomla-book.ru admin, Thanks for the well-written and informative post!