Несколько тегов, разделённых запятой, означают логическое И между ними. Вы также можете использовать точку с запятой в качестве логического ИЛИ. И имеет высший приоритет над ИЛИ. Вы не можете использовать скобки для группировки условий. Звёздочка (*) внутри тега используется в качестве маски для "подстроки".
Разделы: Документация / Расширяем Cotonti / Расширения
Каждый, кому приходилось создавать или изменять шаблоны Cotonti, видел и использовал шаблон теги. Теги - это короткие кусочки кода, которые при разборе (парсинге) системой XTemplate, замененяются на блок HTML-кода. Это обеспечивает существование файла шаблона только в виде HTML-кода. Любой код, сгенерированный PHP, поддерживается с помощью плагина и анализируется с помощью тега.
При разработке плагина, важно знать, как определять теги и условные блоки в системе XTemplate. Раньше большинство плагинов использовали обычный способ получения HTML для разбора и отображения. Хотя использование XTemplate и свой собственный файл шаблона гораздо приятный способ построить свой плагин, вы все еще можете использовать классический способ для standalone плагинов. Это можно сделать с помощью переменных $plugin_title, $plugin_subtitle и $plugin_body. Они автоматически присваиваются тегам {PLUGIN_TITLE}, {PLUGIN_SUBTITLE} и {PLUGIN_BODY}. В этом случае, вам не нужно создавать свой собственный файл шаблона (и вы можете не включать tpl каталог). Cotonti будет использовать plugin.tpl из скина взамен него.
Итак, вы хотите использовать свой собственный файл шаблона. Вы начинаете с определения файла шаблона в качестве нового объекта XTemplate. Это верно, система XTemplate является объектно-ориентированной частью кода. После того как вы создали новый объект XTemplate, вы можете использовать набор методов (функций), поставляемых с классом XTemplate. Мы будем использовать только два из них: assign() и parse(). Сначала мы создаем новый объект XTemplate:
$t = new XTemplate(‘path/to/file.tpl’);
We are using $t as the XTemplate object variable name, but you can use any variable name you like. The ‘path/to/file.tpl’ is the path to the template file, from the Cotonti root folder. While this would work perfectly fine, it’s not a very flexible way to define the template file. Therefore we will use the cot_tplfile() function instead, like this:
$t = new XTemplate(cot_tplfile('pluginname', 'plug'));
Первым параметром является имя файла без расширения. Второй параметр должен быть установлен в 'plug', поскольку мы имеем дело с плагином. Другие возможные значения 'module' и 'core'.Функция cot_tplfile() будет искать правильный путь к файлу шаблона. Имя файла всегда должно начинаться с pluginname. Если вы хотите использовать несколько файлов шаблонов, вы должны использовать имена вроде этого: pluginname.secondary.tpl. Не забудьте опустить расширение при использовании cot_tplfile().
Следующим шагом является назначение некоторых тегов в шаблоне файла. Мы делаем это с помощью метода assign() нашего объекта XTemplate:
$t->assign();
Метод assign() может может принять один тег или массив тегов:
$t->assign('SINGLE_TAG', '<p>Piece of HTML</p>'); $t->assign(array( 'TAG_ONE' => '<p>Piece of HTML</p>', 'TAG_TWO' => $somevariable ));
Как вы можете видеть, очень просто назначить кучу тегов сгенерированного PHP контента. Хотя это хороший способ для реализации шаблонов дизайна MVC, но не очень гибкий. Что делать, если вы хотите отобразить несколько строк контента из базы данных? XTemplate использует HTML-комментарий и метод parse(), чтобы позволить это. Допустим, вы только что выполнили SQL запрос, чтобы получить все страницы. Скорее всего, вы будете использовать цикл while для прохода по строкам. Рассмотрим следующий код:
while($row = $sql->fetch()) { $t->assign(array( 'PAGE_ROW_ID' => $row['page_id'], 'PAGE_ROW_TITLE' => $row['page_title'] )); }
Этот код позволяет переопределять теги в каждой итерации цикла while, и в результате теги будут установлены в значение последней строки. Чтобы предотвратить это, мы должны заставить разбирать теги непосредственно после их определения. Это достигается с помощью метода parse().
$t->parse();
Метод parse() принимает один параметр: блок кода. Блок кода является уникальным кодом, который находится внутри файла шаблона в виде HTML комментариев. Он всегда содержит BEGIN и END, как здесь:
<!-- BEGIN: BLOCK_CODE --> ... <!-- END: BLOCK_CODE -->
Возможно, вы заметили, что каждый файл шаблона Cotonti начинается и заканчивается таким тегом, фактически определяющим весь документ в виде блока. Как правило, это блок MAIN, но вы можете использовать другой, если вы действительно хотите этого.
В PHP-коде плагина мы добавим метод parse() к циклу while:
while($row = $sql->fetch()) { $t->assign(array( 'PAGE_ROW_ID' => $row['page_id'], 'PAGE_ROW_TITLE' => $row['page_title'] )); $t->parse('MAIN.PAGE_ROW'); }
Только что определенный блок называется ‘PAGE_ROW’, а поскольку он будет использоваться в блоке MAIN, мы добавляем блок с названием родительского блока и точку, чтобы разделить их. Наш шаблон может выглядеть следующим образом:
<!-- BEGIN: MAIN --> <h1>{SINGLE_TAG}</h1> <!-- BEGIN: PAGE_ROW --> <p>{PAGE_ROW_TITLE}</p> <!-- END: PAGE_ROW --> <!-- END: MAIN -->
Если вы не хотите или не можете использовать блок MAIN, вы можете заменить его на другой код. Однако это потребует от вас сделать еще один разбор в конце кода плагина. Блок MAIN автоматически анализируется Cotonti, но любой другой блок должен быть обработан вручную вашим плагином. Просто вызовите метод parse() снова, и, наконец, выведите блок (для standalone):
$t->parse('ALTERNATIVE'); $t->out('ALTERNATIVE'); // Only for standalone
Лучше всего делать это непосредственно перед закрывающим тегом PHP.
Разделы: Темы
The Sed-Dark skin from Xiode adapted for Cotonti.
Version for Cotonti < 0.0.6
Version for Cotonti >= 0.0.6
Разделы: Documentation / Extending Cotonti / Themes
You can think of Cotonti as a "dumb machine", it simply picks data from MySQL database and sends it to client (web browser) through a template engine, the "theme".
Theme — a set of files used to programm pages layout and its styling. style named xxx.tpl in folders inside /skins folder (for example: /themes/mytheme)
Template file (usually have .tpl extension) — a file made of simple HTML code, plus some placeholders named "tags"
Tag — special marked place holder to be substituted on templace parsing with some variable content. CoTemplate tags enclosed with curly brackets {}, and can be placed anywhere within HTML code, like this:
<a href="{PHP.cfg.mainurl}" title="{PHP.L.Home}"> {PHP.L.Home} <span>Start here</span> </a>
Nearly all pages (except popups) are built this way:
At the very beginning, Cotonti connects to the MySQL database, grabs some global data, loads the levels, the categories, statistics and perform a load of other actions. At this point nothing is sent to the client (your browser) yet.
Then it loads the file /system/header.php
This file mainly outputs the HTML code for the top of the website.
This is done through the TPL file : themes/…/header.tpl
Then the body of the page is loaded, and same as before, some HTML code is created for the middle of the page, still with a tpl file.
Then the file /system/footer.php is loaded.
It's outputing the HTML code for the bottom of the website.
And once again, this output is done through a TPL file : themes/…/footer.tpl
So a page is almost always made of 3 separate parts:
- The header (the top) : Always header.tpl
- The body of the page (the middle) : A file *.tpl
- The footer (the bottom) : Always footer.tpl
The body can be the the home page, the forums, an event, userlist, the administration panel, a plugin, etc.
Basically a "theme" is a set of TPL files, TPL stands for "templates".
A TPL file is made of HTML code, plus placeholders named "tags".
In almost all pages, the HTML send to the client browser is made of 3 TPLs, added one after the other, in this order :
For example, Cotonti will output the homepage using : header.tpl + index.tpl + footer.tpl
For the forums home it will be: header.tpl + forums.sections.tpl + footer.tpl
So if you plan to build your own theme, the fastest and easiest way is to go with an official development theme (i.e. Nemesis) and first start to tweak header.tpl, footer.tpl and the CSS file. By editing those only 3 files you can quickly get interesting results.
For some reasons, the popups for the ratings and the polls do not follows this, those standalone pages have their own header and footer in their main TPL file.
Tags are looking like this : {XXX_YYY}
In short, a tag is an object dynamically created by the PHP code, inside there're values such as strings, HTML code, URLs, pictures, etc.
Note: that tags that are not "global" will only work in a given TPL file. The name of the tag often tells where this tag is valid
(for example: tag {PAGE_XXX} will only work in page.tpl, {COMMENTS_XXX} will only work in comments.tpl and so on).
To see the list of tags available on the current page, append &tpl_debug=1 to the page parameters (more info about debuggin themes).
Global tags are a special kind of tags, valid in all skin files.
Most of the time, those tags are coming from PHP code variables, or from the configuration table, or from global plugins.
All global tags are looking like this : {PHP.tagnamehere}
For the complete list of global tags, you can insert a vardump for PHP tag in your template: {PHP|dump}. This feature is available since 0.9.1.
Sample, some fairly common global tags :
{PHP.cfg.adminemail}
{PHP.cfg.maintitle}
{PHP.cfg.mainurl}
{PHP.usr.name}
{PHP.usr.id}
{PHP.out.copyright}
Разделы: Documentation (Genoa and older) / Dutch / Skins
{ADMIN_MAIN}en verander het in:
<div id="pagtab"> {ADMIN_MAIN} </div>
Разделы: Documentation (Genoa and older) / English / Skins
{ADMIN_MAIN}and change it to:
<div id="pagtab"> {ADMIN_MAIN} </div>
Разделы: Documentation (Genoa and older) / English / Skins
<tr> <td>{PHP.L.Begin}:</td> <td>{PAGEADD_FORM_BEGIN}</td> </tr>
<!-- BEGIN: ADMIN --> <tr> <td>{PHP.L.Parser}:</td> <td>{PAGEADD_FORM_TYPE}</td> </tr> <!-- END: ADMIN -->
Разделы: Documentation (Genoa and older) / Dutch / Skins
<tr> <td>{PHP.L.Begin}:</td> <td>{PAGEADD_FORM_BEGIN}</td> </tr>
<!-- BEGIN: ADMIN --> <tr> <td>{PHP.L.Parser}:</td> <td>{PAGEADD_FORM_TYPE}</td> </tr> <!-- END: ADMIN -->
Разделы: Documentation (Genoa and older) / Türkçe / Temalar
<!-- IF {PHP.tag_i} > 0 -->, <!-- ENDIF --><a href="{PAGE_TAGS_ROW_URL}">{PAGE_TAGS_ROW_TAG}</a>değiştirin:
<!-- IF {PHP.tag_i} > 0 -->, <!-- ENDIF --><a href="{PAGE_TAGS_ROW_URL}">{PAGE_TAGS_ROW_TAG}</a>
<!-- BEGIN: DOWNLOAD --> {PAGE_FILE_ICON}<a href="{PAGE_FILE_URL}">{PHP.L.Download}: {PAGE_SHORTTITLE}</a><br/> <!-- END: DOWNLOAD -->değiştirin:
<!-- BEGIN: DOWNLOAD --> {PAGE_FILE_ICON}<a href="{PAGE_FILE_URL}">{PHP.L.Download}: {PAGE_FILETITLE}</a><br/> <!-- END: DOWNLOAD -->
<div class="pagnav">{PAGE_PAGEPREV} {PAGE_PAGNAV} {PAGE_PAGENEXT}</div>değiştirin:
<div class="paging">{PAGE_PAGEPREV} {PAGE_PAGENAV} {PAGE_PAGENEXT}</div>
Разделы: Documentation (Genoa and older) / Dutch / Skins
<!-- IF {PHP.tag_i} > 0 -->, <!-- ENDIF --><a href="{PAGE_TAGS_ROW_URL}">{PAGE_TAGS_ROW_TAG}</a>met
<!-- IF {PHP.tag_i} > 0 -->, <!-- ENDIF --><a href="{PAGE_TAGS_ROW_URL}">{PAGE_TAGS_ROW_TAG}</a>Verschil is de spatie na -->,
<!-- BEGIN: DOWNLOAD --> {PAGE_FILE_ICON}<a href="{PAGE_FILE_URL}">{PHP.L.Download}: {PAGE_SHORTTITLE}</a><br/> <!-- END: DOWNLOAD -->met
<!-- BEGIN: DOWNLOAD --> {PAGE_FILE_ICON}<a href="{PAGE_FILE_URL}">{PHP.L.Download}: {PAGE_FILETITLE}</a><br/> <!-- END: DOWNLOAD -->
<div class="pagnav">{PAGE_PAGEPREV} {PAGE_PAGNAV} {PAGE_PAGENEXT}</div>met
<div class="paging">{PAGE_PAGEPREV} {PAGE_PAGENAV} {PAGE_PAGENEXT}</div>
Разделы: Documentation (Genoa and older) / English / Skins
<!-- IF {PHP.tag_i} > 0 -->, <!-- ENDIF --><a href="{PAGE_TAGS_ROW_URL}">{PAGE_TAGS_ROW_TAG}</a>with
<!-- IF {PHP.tag_i} > 0 -->, <!-- ENDIF --><a href="{PAGE_TAGS_ROW_URL}">{PAGE_TAGS_ROW_TAG}</a>Difference is the space after -->,
<!-- BEGIN: DOWNLOAD --> {PAGE_FILE_ICON}<a href="{PAGE_FILE_URL}">{PHP.L.Download}: {PAGE_SHORTTITLE}</a><br/> <!-- END: DOWNLOAD -->with
<!-- BEGIN: DOWNLOAD --> {PAGE_FILE_ICON}<a href="{PAGE_FILE_URL}">{PHP.L.Download}: {PAGE_FILETITLE}</a><br/> <!-- END: DOWNLOAD -->
<div class="pagnav">{PAGE_PAGEPREV} {PAGE_PAGNAV} {PAGE_PAGENEXT}</div>with
<div class="paging">{PAGE_PAGEPREV} {PAGE_PAGENAV} {PAGE_PAGENEXT}</div>
Разделы: Themes
Skin converted from ChocoTemplates.com
Original template demo
The menu-structure can be found in the readme-file
Разделы: Documentation (Genoa and older) / English / Skins
/* ============== Ratings CSS ============== */
<td colspan="2" class="valid">
<input type="submit" value="{PHP.skinlang.pageadd.Submit}" />
</td>
<td colspan="2" class="valid">
<!-- IF {PHP.usr_can_publish} -->
<input name="rpublish" type="submit" class="submit" value="{PHP.L.Publish}" onclick="this.value='OK';return true" />
<input type="submit" value="{PHP.L.Putinvalidationqueue}" />
<!-- ELSE -->
<input type="submit" value="{PHP.L.Submit}" />
<!-- ENDIF -->
</td>
PHP.L.plu_therescurrently} {WHOSONlINE_VISITORS} {PHP.L.plu_visitors} {WHOSONlINE_MEMBERS} {PHP.L.plu_members}<br /> <br />
PHP.L.plu_therescurrently} {WHOSONlINE_VISITORS} {WHOSONlINE_TEXTVISITORS} {WHOSONlINE_MEMBERS} {WHOSONlINE_TEXTMEMBERS}<br /> <br />
Разделы: Themes
Разделы: News / Announcements