In-Portal Developers Guide

This is a wiki-based Developers Guide for In-Portal Open Source CMS. The purpose of this guide is to provide advanced users, web developers and programmers with documentation on how to expand, customize and improve the functionality and the code the In-Portal software. Please consider contributing to our documentation writing effort.

K4:Базовые сведения о тэгах и шаблонах

From In-Portal Developers Guide

Jump to: navigation, search
Line 57: Line 57:
{{InfoBox|All class names, registered in the class factory are [[K4:Cache|cached]] so we must reset cache before changes will take effect.}}
{{InfoBox|All class names, registered in the class factory are [[K4:Cache|cached]] so we must reset cache before changes will take effect.}}
-
=== Добавление тэга в обработчик тэгов ===
+
=== Adding a Tag to the Tag Processor ===
-
После того, как успешно создан или найден класс [[TagProcessor:About|обработчика тэгов]], можно приступать к созданию метода, результат работы которого и будет выведен на странице, как результат работы нового тэга. Сам метод будет располагаться в классе обработчика тэгов. Согласно [[K4:Назначение имён#Функции и методы|правилу именования тэгов]] каждое слово в названии метода должно начинаться с большой буквы. Также название данного метода может содержать только латинские буквы и цифры. Цифры желательно не использовать.
+
-
Синтаксический анализатор (<code>template parser</code>) при вызове метода, связанного с найденным им в шаблоне тэгом также будет передать ассоциативный массив параметров, переданных в сам тэг в качестве первого аргумента метода. Это будет наглядно показано на приведённом ниже примере:
+
After successfully creating or finding the class of the [[TagProcessor:About|tag processor]], we can start writing the method whose output will be displayed on the page as a result of the new tag. The method itself will be located in the class of the tag processor. Following [[K4:Назначение имён#Функции и методы|tag naming conventions]], each word in the method name must start with a capital letter. Also, each method's name may contain only Latin letters and numbers, although it's preferred that numbers aren't used.
 +
 
 +
The (<code>template parser</code>) upon calling the method indicated in the tag in the template will also pass an associative array of parameters, passed to the tag itself as the first argument of the method. This is illustrated in the following example:
<source lang="php">
<source lang="php">
Line 78: Line 79:
</source>
</source>
-
На шаблоне вызов тэга выглядит следующим образом:
+
In the template, the tag call looks like this:
<source lang="xml">  
<source lang="xml">  
<inp2:sample-prefix_PrintHelloWorld />
<inp2:sample-prefix_PrintHelloWorld />
Line 89: Line 90:
|-
|-
| '''<code>sample-prefix</code>''' || Название префикса тега.  
| '''<code>sample-prefix</code>''' || Название префикса тега.  
 +
|}
 +
 +
{| class="prettytable"
 +
! Text|| Description
 +
|-
 +
| '''<code>inp2</code>''' || Namespace tag that the <code>template parser</code> processes.
 +
|-
 +
| '''<code>sample-prefix</code>''' || Name of tag's prefix.
|}
|}

Revision as of 17:10, 13 March 2009

Работа с шаблонами Работа с шаблонами
Статьи в этой категории

This is an introductory article in a series of articles describing the In-Portal CMS template parser.

The template parser parses templates (files with the ".tpl" file extension) and renders them in HTML. For this the system uses one main PHP file ("index.php" on the front end website and "admin/index.php" in the administrative console), through which all tags are processed, to output HTML to the browser.

Image:Infobox Icon.gif
  • Templates are used for separating business logic from the visual design of the site. You will not find any files in In-Portal CMS containing PHP and HTML together!
  • Although the tags used by the template parser contain a lot of functionality, they are by no means to be considered an additional programming language, because for that we have PHP!

The template parser processes only [http://www.w3schools.com/xml/xml_dtd.asp well formed XML tags with the namespace inp2. This article will discuss the basics of templates and tags, specifically:

  • Creating a tag from the start;
  • Tag and template parameters;
  • Parameter scope;
  • Examples and restrictions/limitations of working with tags and templates.


Contents

Adding a New Tag

Adding a tag can be broken down into the following steps:

  • Deciding on the location of the body of the tag in the class structure of the project's tag processors;
  • Creating a new class, that's going to contain the body of the tag (if necessary);
  • Registering the new tag in factory.php class (only if a class was created in the previous step);
  • Writing the body of the tag in the chosen or created tag processor.

Following we'll discuss the details of each of the above stages of creating a tag.

Tag Placement

In most cases, a new tag should be placed in the tag processor, with the prefix that it's using. For example, if there's an "int_Tests" table for the "test" prefix, then the tag that's using this table would be located in the tag processor (e.g. "TestTagProcessor"), that's tied to the "test" prefix.

Creating a Tag Processor

Creating a tag processor starts with creating the file, which will contain the tag processor class. The naming convention for files that contain classes is as follows, the filename is formed by replacing all dashes in the prefix with an underscore followed by tp.php, e.g. "sample_prefix_tp.php". The tag processor file must be in the same directory that contains the unit config, which indicates where it's registered in the class factory. For example, for the prefix "sample-prefix", the directory would be "custom/units/sample_prefix".

Furthermore, in the above created file, it's required to define the tag processor class. The Class name for the tag processor is formed based on the prefix as follows:

  • the first letter of each word in the prefix is capitalized;
  • all dashes are removed;
  • "TagProcessor" is added to the resulting line.

For example, if the prefix is "sample-prefix", then the class of its tag processor is going to be called "SamplePrefixTagProcessor". This class must be the child of the class "kDBTagProcessor":

class SamplePrefixTagProcessor extends kDBTagProcessor {
 
}

The final step in creating new tag processors is registering in the class factory. The tag processor class is registered using the key TagProcessorClass in the config file for the prefix to which it will be connected. In the present example, that prefix is "sample-prefix". To register the tag processor, we must specify the name of the tag processor class and the file where its declared. This is illustrated in the below example.

$config = Array (
	'Prefix' => 'sample-prefix',
	'TagProcessorClass' =>	Array ('class' => 'SamplePrefixTagProcessor', 'file' => 'sample_prefix_tp.php', 'build_event' => 'OnBuild'),
);

The key that wasn't described above is called "build_event", that is used for the event task, which will initialize the object. For tag processor classes, this will always be the event OnBuild.

Image:Infobox Icon.gif All class names, registered in the class factory are cached so we must reset cache before changes will take effect.

Adding a Tag to the Tag Processor

After successfully creating or finding the class of the tag processor, we can start writing the method whose output will be displayed on the page as a result of the new tag. The method itself will be located in the class of the tag processor. Following tag naming conventions, each word in the method name must start with a capital letter. Also, each method's name may contain only Latin letters and numbers, although it's preferred that numbers aren't used.

The (template parser) upon calling the method indicated in the tag in the template will also pass an associative array of parameters, passed to the tag itself as the first argument of the method. This is illustrated in the following example:

class SamplePrefixTagProcessor extends kDBTagProcessor {
 
	/**
	 * Tag description
	 *
	 * @param Array $params
	 * @return string
	 */ 
	function PrintHelloWorld($params)
	{
		return 'Hello World! Param Value: [' . $params['sample_param'] . ']';
	}
}

In the template, the tag call looks like this:

<inp2:sample-prefix_PrintHelloWorld />
текст описание
inp2 Пространство имён тэгов, которое синтаксический анализатор (template parser) обрабатывает.
sample-prefix Название префикса тега.
Text Description
inp2 Namespace tag that the template parser processes.
sample-prefix Name of tag's prefix.

Парные и непарные тэги

Все, обрабатываемые синтаксическим анализатором (template parser) тэги делятся на парные и непарные. Парные тэги от непарных отличаются тем, что они могут использовать заключённое в них содержание по своему усмотрению. Все, объявленные в классах обработчиков тэгов тэги непарные. В свою очередь все парные тэги системные и не подлежат переопределению. В общем виде парные и непарные тэги выглядят так:

непарный тэг:
<inp2:prefix.special_TagName param1="value1" param2="value2"/>
 
парный тэг:
<inp2:prefix_TagName param1="value1" param2="value2">
содержание тэга
</inp2:prefix_TagName>
Image:Tipbox Icon.gif Для разделения параметров тэга и его самого допускается использование любого количества разделительных символов (whitespace).

Ниже приведены примеры использования нескольких популярных тэгов.

  • Непарные тэги:
а) <inp2:m_TemplatesBase module="Custom"/> - путь к папке с файлами темы модуля Custom.
б) <inp2:m_GetConfig var="Site_Name"/> - переменная конфигурации Site_Name.
с) <inp2:st_PageInfo type="meta_title"/> - название текущей страницы.
  • Парные тэги:
а) Тэг условия.
<inp2:m_if check="m_Param" name="is_last">
...
</inp2:m_if>
 
б) Тэг определения блочного элемента в шаблоне.
<inp2:m_DefineElement name="menu_block">
	<td><inp2:m_Phrase name="lu_about_us"/></td>
</inp2:m_DefineElement>

Общая форма вызова тэга из шаблона

В общем виде форма вызова тэга на шаблоне имеет вид:

<inp2:prefix[.special]_TagName param1="value1" other_param='value2'/>
параметр описание
prefix (string) Префикс тэга, например "test".
special (string) Special тэга, например "front". Если указан, то отделяется от префикса при помощи символа точки (".").
TagName (string) Название тэга, например "PrintHelloWorld". Если тэг нигде не определён, то синтаксический анализатор (template parser) расценит это как критичную ошибку (fatal error) и прекратит выполнение всех последующих тэгов на текущем шаблоне.
param1="value1" Пара параметр и его значение, которые можно передать в тэг. В тэг может передаваться неограниченное количество параметров. Названия параметров должны быть уникальными в пределах одного тэга, а также должны состоять только из латинских букв и цифр.
other_param='value2' Также является допустимой формой задания значения параметра в тэге. Рекомендуется использовать тогда, когда сам тэг применяется в качестве значения атрибута HTML-тэга. В таком случае не будет нарушена подсветка синтаксиса в шаблоне (если используется редактор шаблонов с подсветкой синтаксиса). Это будет показано на ниже приведённом примере.
<img src="<inp2:m_TemplatesBase module='custom'/>img/spacer.gif" alt=""/>

Пример вызова тэга на шаблоне:

<inp2:test.front_PrintHelloWorld current_datetime="yes" />

Пример функции в классе TestTagProcessor

/**
 * Printing sample text and current date, when additional parameter is given
 *
 * @param Array $params
 * @return string
 */ 
function PrintHelloWorld($params)
{
	// проверка на special
	$ret = $this->Special == 'front' ? 'Hello World Front !' : 'Hello World !';
 
	// проверка установлен ли параметр 'current_datetime'	
	if (array_key_exists('current_datetime', $params) && ($params['current_datetime'] == 'yes')) {
		$ret .= ' ' . adodb_date('m/d/Y H:s');
	}
 
	return $ret;
}

Задание параметров по умолчанию

Параметры по умолчанию позволяют задать значения параметров для парных (блочных) тэгов и для шаблонов на тот случай, если эти тэги или шаблоны будут использоваться без передачи в них всех, используемых в них параметров.

Параметры шаблона по умолчанию

Параметры шаблона по умолчанию задаются вверху шаблона при помощи тэг m_DefaultParam. Если в теле такого шаблона будет использоваться такой параметр, но его значение не будет передано при вызове шаблона, то будет использовано значение по умолчанию. Это будет показано на ниже приведённом примере.

=== include_test.tpl ===
<inp2:m_DefaultParam param1="default_value1" param2="default_value2"/>
 
PARAM: [<inp2:m_Param name="param2"/>]
 
=== index.tpl ===
// выведет PARAM: [default_value2]
<inp2:m_include template="include_test"/>
 
// выведет PARAM: [given_value]
<inp2:m_include template="include_test" param2="given_value"/>

Параметры парного тэга по умолчанию

Параметры по умолчанию для парных тэгов задаются при их определении. Это будет показано на ниже приведённом примере.

<!-- определение блока -->
<inp2:m_DefineElement name="sample_element" as_label="" currency="USD">
	[<inp2:m_Param name="as_label"/> - <inp2:m_Param name="currency"/>]
</inp2:m_DefineElement>
 
<!-- использование блока передавая ему параметры -->
<inp2:m_RenderElement name="sample_element" as_label="1"/> // даст [1 - USD]
 
<!-- использование блока не передавая ему параметры -->
<inp2:m_RenderElement name="sample_element"/> // даст [ - USD]

Расположение шаблонов

Все шаблоны делятся на 2 группы по месту их применения:

  • административная консоль;
  • пользовательская часть сайта.

Далее будут описаны особенности расположения и использования шаблонов из обеих выше упомянутых групп.

Шаблоны в административной консоли

В административной консоли все шаблоны разделены по модулям. В каждом модуле в свою очередь есть директория "admin_templates", в которой содержатся все его шаблоны. Например если модуль называется "proj-base", то его шаблоны буду лежать в директории "proj-base/admin_templates". Под директорией "admin_templates" допускается создание других директорий для логической группировки шаблонов в пределах одного модуля. При использовании шаблона всегда следует писать название модуля перед названием шаблона, напр. "proj-base/users/users_list", а не просто "users/users_list". Если требуется подключить (include) оригинальную версию шаблона (если шаблон был подменён через ReplacementTemplates) то нужно написать "orginal:" перед названием шаблона, напр. "original:path/to/replaced/template".

Image:Tipbox Icon.gif Название модуля писать не обязательно только для шаблонов из директории "core/admin_templates".
Image:Infobox Icon.gif В проектах разрешается создавать и изменять только шаблоны административной консоли, находящиеся в папке "custom/admin_templates", т.е. принадлежащие модулю "custom".

Шаблоны на пользовательской части сайта

На пользовательской части сайта все шаблоны разделены по темам (styles). Для каждой темы существует директория вида "themes/<theme_name>", где "<theme_name>" это значение поля Name конкретной темы. Все темы задаются в секции "Configuration -> Themes". Обычно достаточно создать папку с темой и шаблоны в ней и нажать кнопку "Rebuild Theme Files" на панели инструментов в списке тем для того, чтобы запись в таблице Theme создалась автоматически. Например, если путь к шаблону относительно корневой директории проекта "themes/theme_test/testing/sample_template.tpl", то для использования этого шаблона нужно указывать "testing/sample_template". При этом шаблон будет искаться в той теме сайта, которая указана в ссылке на сайт.

Image:Tipbox Icon.gif В проектах на платформе обычно используется только одна тема, с названием "theme_<project_name>", напр. "theme_fuse".

Область действия параметров

По умолчанию параметры переданные в блок или шаблон будут видны только в нём самом. Если требуется, передать значение индивидуального параметра в следующий блок или шаблон, то это можно сделать при помощи следующей конструкции param_name="$param_name". Если требуется передать все параметры из шаблона или блока в следующий шаблон, то это можно сделать указав параметр "pass_params". Все выше описанные варианты будут показаны на ниже приведённом примере.

== main.tpl ==
<inp2:m_DefaultParam main_param="sample_value" main_param2="test"/> <!-- Установка значения по умолчанию для параметров "main_param" и "main_param2". -->
 
<inp2:m_DefineElement name="sample_element">
	main param: [<inp2:m_Param name="main_param"/>]
	main param2: [<inp2:m_Param name="main_param2"/>]
</inp2:m_DefineElement>
 
<!-- Значение всех параметров из этого шаблона не будут доступны в подключаемом шаблоне и используемом блоке. -->
<inp2:m_include template="include_test"/>
<inp2:m_RenderElement name="sample_element"/>
 
<!-- Только значение параметра "main_param" будет доступно в подключаемом шаблоне и используемом блоке. -->
<inp2:m_include template="include_test" main_param="$main_param"/>
<inp2:m_RenderElement name="sample_element" main_param="$main_param"/>
 
<!-- Только значение параметра "main_param2", но под именем "main_param" будет доступно в подключаемом шаблоне и используемом блоке. -->
<inp2:m_include template="include_test" main_param="$main_param2"/>
<inp2:m_RenderElement name="sample_element" main_param="$main_param2"/>
 
<!-- Значения всех параметров этого шаблона будут доступны в подключаемом шаблоне и используемом блоке. -->
<inp2:m_include template="include_test" pass_params="true"/>
<inp2:m_RenderElement name="sample_element" pass_params="true"/>
 
== include_test.tpl ==
main param: [<inp2:m_Param name="main_param"/>]
main param2: [<inp2:m_Param name="main_param2"/>]

Назначения имён параметрам

Название параметра тэга, в котором передаётся название блока должно называться "render_as". В случае, когда в тэг передаётся несколько названий блоков, то названия параметров, в которых передаются названия блоков должны заканчиваться на "_render_as", напр. "user_render_as". Это будет показано на ниже приведённом примере.

<inp2:sample-prefix_PrintList render_as="sample_element" more_render_as="more_element"/>

Параметры, используемые на шаблоне при его компиляции превращаются в PHP-переменные и поэтому их название должно соответствовать тем же правилам, что и остальные наименования в PHP. Правильное название параметра должно начинаться с буквы или символа подчёркивания с последующими в любом количестве буквами, цифрами или символами подчёркивания.

Значение параметров по умолчанию

Если не задавать значения по умолчанию для необязательных параметров шаблона или блока, то при их (шаблона или блока) использовании будут выдаваться php warnings, что есть не очень хорошо. Для нахождения мест в шаблоне, где не заданы значения параметров по умолчанию лучше всего подходит отладчик.