ВходПользовательПароль
   
Регистрация
Регистрация
Помощь
Помощь
Поиск
Поиск
Gosudar.com.ru  
  

Меню сайта
Навигация
Объявления Объявления
Блоги Блоги
Файловый архив Файловый архив
Последние Последние
Гостевая Гостевая
Контакты Контакты
Личный Раздел
Вход Вход
Регистрация Регистрация
Cms R3-born
Библиотека Библиотека
Файлы R3-born Файлы R3-born
Разработка(блог) Разработка(блог)
Демо-модули
Фотоальбом Фотоальбом
Новости Новости
Форум Форум

Счётчик
5651956519565195651956519
Главная » Библиотека

Библиотека

Библиотека  » CMS R3-born  » Документация
Template Engine (Basics)
Описание Manual. English
Автор martin Число Январь 04 2008, 22:31 Тип FAQ
Категория Документация
Просмотров 2172
Трекбек URL для этой записи: Трекбек
  Голосов 0


Template Engine (Basics)
Manual. English
This article will hopefully shed some light on the usage of R3-born template system to enable developers to write their own template files properly without much confusion.

Syntax

The R3-born templating syntax is actually very easy. The amount of variables on any one page may seem daunting at first, but each one only represents a piece of information. Together with the html around them they produce the interface and information that R3-born presents to you. The R3-born variable system is very easy to pickup because every variable is held inside braces ( {Braces} ). Variables are always in upper-case, because this is how the template engine processes them. For you to easily identify what each variable means, the following standards have been adopted.

  • The prefix U_ is a URL variable. These should always be used instead of directly linking to the php page, to allow R3-born to control the URI session ids.
  • The prefix L_ is a language variable. These should always be used instead of directly using your language in order to allow to multi-lingual sites to use localisations without confusion.
  • The prefix S_ is a form variable. These variables control everything about a form, from the action, to form fields such as hidden fields and select boxes. Not all form fields are represented by a variable, only fields which need to be controlled by R3-born.
  • The suffix _IMG is an image variable. These images are controlled by the R3-born code itself. All these images however are specified in the template config file.


Switches and Loops

These are one of the most important parts of R3-born templates. Switches are however different to loops. Switches hide/show information depending on circumstances, and Loops, loop through information such as rows of data. Switches and loops are held inside HTML comments:

<!-- BEGIN name -->
<!-- END name -->

Switches

Switches hide/show information on certain circumstances. The variable contents of switches do not get derived from the switch name. Switches usually contain the word switch or toggle. Switches and loops are case sensative, and are usually only in lower case.

Loops

Loops are different to switches, in that they always show information. Loops are designed so that the R3-born code can loop through the contents of the loop for every field in the database, for example showing every single user. Variable names contained within, however are derived from the loop name, for example: {user.USERNAME}. The variable name is still upper-case as seen in the example above.

Loops and Switches are described in more detail below.

Creating a new template file
A template file can have any extension, but by R3-born standards, we prefer that you limit it to the extension .tpl (makes it compatible with most/all filesystems and allows other programmers to know where the templates are stored in an easier fashion). The file itself is plaintext/html, with just a couple of extra html-style tags that allow you to format your template data properly.

Specifying a template file
To begin with, you need to include the standard R3-born module code (if it hasn't been included already) to gain access to the template, amongst other things.

 Код:  
if ( !defined('IN_R3BORN') )
{
    die('Hacking attempt');
}

//
// Start session management
//
$userdata = session_pagestart($user_ip, PAGE_MY_MODULE);
init_userprefs($userdata);
//
// End session management


The template inclusion is fairly easy:

 Код:  

$template->set_filenames(array(
      'body' => 'your_template.tpl')
);


It's also a good idea at this point to get the header specified (if it hasn't been already), assuming you want the normal R3-born header. This will also let you set the title of the page:

 Код:  
page_header($lang['My_module_title']); // You'll have to set this in a $lang file somewhere


Just be sure that you remember to render it at the end of the file:

 Код:  
$template->pparse('body');


Don't do this before you've finished passing variables to the template engine... anything you do afterwards won't be included! The 'body' in pparse() corresponds to the 'body' in set_filenames()

Finally, you want to include the page footer (if it hasn't been already):

 Код:  
page_footer();


Basic template variables
There are two sides to making a template variable. The first side is the .php side, to generate the data that goes into the variable. The second is the .tpl side, which shows where in the document the variable goes.

PHP-side
Once you've specified your template file, you can set a template variable as follows:
 Код:  
$template->assign_var('VARIABLE' , $value );


Template-side
Inside the template, you would put the associated variable wherever you will in the html, surrounded by curly braces { }:

 Код:  
{VARIABLE}


The names of the template variables can contain both lower and uppercase letters (a-zA-Z), numerical digits (0-9), the hyphen (-), and the underscore (_), however, standard R3-born code uses only uppercase letters, numbers, and underscore.

If you want to set more than one variable at the same time, you can do this as follows:

PHP-side

 Код:  

$template->assign_vars(array(
      'VARNAME1' => $phpstringval1,
      'VARNAME2' => $phpstringval2,
      'VARNAME3' => $phpstringval3,
      ... etc ..
      'VARNAMEn' => $phpstringvaln
      )
);


Template-side

 Код:  
{VARNAME1} {VARNAME2} {VARNAME3} ... etc ... {VARNAMEn}


Switches
Switches are like "optional" parts of the template. They only appear if the switch is set. If the switch is not set, it's simply not shown.

PHP-side
Creating a switch is pretty easy. Just test whether you want it turned on or not, then use the template's assign_block_vars() to set it accordingly:

 Код:  
if ( $userdata['session_logged_in'] )
{
     $template->assign_block_vars('switch_user_logged_in',array() );
}


Template-side
Inside the template, you would set the associated tags as follows:

 Код:  
<!-- BEGIN switch_user_logged_in -->
... stuff that only shows up when the user is logged in...
<!-- END switch_user_logged_in -->


Note that it's important that the <!-- BEGIN ... --> and <!-- END ... --> appear on their own lines otherwise they might not work. There is also a way to do an "if - else" kind of switch, see the R3-born Template Engine (Advanced) for more detials. However, there is another way of getting around "if - else" requirements as you'll see:

PHP-side

 Код:  
if ( $userdata['session_logged_in'] )
{
     $template->assign_block_vars('switch_user_logged_in',array() );
}
else
{
     $template->assign_block_vars('switch_user_logged_out',array() );
}



Template-side

 Код:  
<!-- BEGIN switch_user_logged_in -->
... stuff that only shows up when the user is logged in...
<!-- END switch_user_logged_in -->
<!-- BEGIN switch_user_logged_out -->
... stuff that only shows up when the user is logged out...
<!-- END switch_user_logged_out -->


Loops
Now we're going to start getting into some more complicated stuff. What happens if you want to show something more than once? You could duplicate the html in your template, which is easy enough, but what happens if this is non-static, and instead specified in the PHP?

For example, lets say we want to repeat some text 10 times:

PHP-side
This is very similar to making a switch, except you're calling the same string in assign_block_vars() multiple times.

 Код:  
$n = 10;
for ( $i = 0; $i < $n; $i++ )
{
     $template->assign_block_vars('my_loop',array() );
}


Template-side
This side is pretty much the same:

 Код:  
<!-- BEGIN my_loop -->
This text will show up ten times
<!-- END my_loop -->


That was pretty simple. But it's not very useful... unless of course, you have different data in each of the loop iterations, which brings us to...

Loop variables
Have you been wondering what that empty array() in assign_block_vars() is all about? This is it. Lets say you want in each loop iteration to say which iteration it is, out of however many there are:

PHP-side
Similar to the way we had regular template variables, we specify loop variables inside the loop array()

 Код:  
$n = 10;
for ( $i = 0; $i < $n; $i++ )
{
     $template->assign_block_vars('my_loop',array(
           'THIS_LOOP' => ($i + 1),
           'TOTAL_LOOPS' => $n
           )
     );
}


Template-side

 Код:  
<!-- BEGIN my_loop -->
This text will show up ten times (this is #{my_loop.THIS_LOOP} of {my_loop.TOTAL_LOOPS} )
<!-- END my_loop -->


An important thing to notice here is that before the variable, you need to put the loop name followed by a dot (.), if you don't, the template engine will think it's a regular template variable, and (probably) won't find a match, and so it won't display anything.

You'll notice that the value of TOTAL_LOOPS is always the same. This is a bit of a waste, because we're storing TOTAL_LOOPS for each loop, but there's only one value. As long as it's within the same loop structure at a higher level, (if you don't understand what that means, don't worry) you can display variables that aren't in that loop's scope:

PHP-side

 Код:  
$n = 10;
$template->assign_vars(array ( 'TOTAL_LOOPS' => $n ) );
for ( $i = 0; $i < $n; $i++ )
{
      $template->assign_block_vars('my_loop',array(
            'THIS_LOOP' => ($i + 1)
            )
      );
}


Template-side

 Код:  
<!-- BEGIN my_loop -->
This text will show up ten times (this is #{my_loop.THIS_LOOP} of {TOTAL_LOOPS} )
<!-- END my_loop -->


Here's another, more complicated (and more applicable) example:
List all the users with user_id between 1 and 25

PHP-side

 Код:  
$sql = "SELECT user_id, username FROM " . USERS_TABLE . " WHERE user_id >= 1 AND user_id <= 25";
if ( ! ( $result = $db->sql_query($sql) ) )
{
      message_die(GENERAL_ERROR, 'Error retrieving user data', '', __LINE__, __FILE__, $sql);
}
while ( $row = $db->sql_fetchrow($result) )
{
      $template->assign_block_vars('user_row',array(
            'USERNAME' => htmlspecialchars($row['username']),
            'USER_ID' => $row['user_id']
            )
      );
}


Template-side

 Код:  
<table>
<!-- BEGIN user_row -->
  <tr>
    <td>{user_row.USER_ID}</td>
    <td>{user_row.USERNAME}</td>
  </tr>
<!-- END user_row -->
</table>


Nested loops/switches
This is where it sometimes gets tricky, and developers get confused. What happens if you want a loop or a switch inside another loop or switch?

For example, you want to show a list of the first twenty-five users, and their emails, but only show the emails if the user looking at the page is an administrator? Let's add a bit to our last example:

PHP-side

 Код:  
$sql = "SELECT user_id, username, user_email FROM " . USERS_TABLE . " WHERE user_id >= 1 AND user_id <= 25";
if ( ! ( $result = $db->sql_query($sql) ) )
{
      message_die(GENERAL_ERROR, 'Error retrieving user data', '', __LINE__, __FILE__, $sql);
}

while ( $row = $db->sql_fetchrow($result) )
{
      $template->assign_block_vars('user_row',array(
            'USERNAME' => htmlspecialchars($row['username']),
            'USER_ID' => $row['user_id'],
            'USER_EMAIL' => $row['user_email']
            )
      );

      if ( $userdata['user_level'] == ADMIN )
      {
            $template->assign_block_vars('user_row.switch_admin',array());
      }
}


Template-side

 Код:  
<table>
<!-- BEGIN user_row -->
  <tr>
    <td>{user_row.USER_ID}</td>
    <td>{user_row.USERNAME}</td>
    <!-- BEGIN switch_admin -->
    <td>{user_row.USER_EMAIL}</td>
    <!-- END switch_admin -->
</tr>
<!-- END user_row -->
</table>


Some important things to notice are that in the PHP, the name of the switch is 'user_row.switch_admin', but in the template, the name is only 'switch_admin', which inside 'user_row'. This means that you can't create two switches in the same scope and expect them to work inside each other:

PHP-side

 Код:  
$template->assign_block_vars('switch_user_logged_in',array() );
$template->assign_block_vars('switch_admin',array() );


Template-side

 Код:  
<!-- BEGIN switch_user_logged_in -->
<!-- BEGIN switch_admin -->
some text if it's an admin, logged in
<!-- END switch_admin -->
<!-- END switch_user_logged_in -->


The above won't work, because the template engine will look for 'switch_user_logged_in.switch_admin', and it won't find it. One way to do get around this would be:

 Код:  
$template->assign_block_vars('switch_user_logged_in',array() );
$template->assign_block_vars('switch_user_logged_in.switch_admin',array() );


Alternatively, you could have a separate switch altogether. There are actually several different wats of doing this properly, if you think about it.

Nested loop variables

Just so that you know this works (to probably any depth)

Lets say for example you have an array of users, each of which has a name and id attribute, as well as a 'friends' attribute which is an array of the names of their friends, and you want to show the list of users, and who their friends are:

PHP-side

 Код:  
for ($i = 0; $i < count($dataset); $i++ )
{
      $template->assign_block_vars('user_row', array(
            'USER_ID' => $dataset[$i]['user_id'],
            'USER_NAME' => $dataset[$i]['user_name']
            )
      );

      for($j = 0; $j < count($dataset[$i]['friends']); $j++ )
     {
            $template->assign_block_vars('user_row.friend_row',array(
                  'NAME' => $dataset[$i]['friends'][$j]
                  )
            );
     }
}


Template-side

 Код:  
<table>
<!-- BEGIN user_row -->
  <tr>
    <td>{user_row.USER_ID}</td>
    <td>{user_row.USERNAME}</td>
    <td>
      <table>
      <!-- BEGIN friend_row -->
        <tr><td>{user_row.friend_row.NAME}</td></tr>
      <!-- END friend_row -->
      </table>
    </td>
  </tr>
<!-- END user_row -->
</table>


Assigning Vars from handle
You can also create independant "sub" template files to avoid massive switch statements. For example, the pollbox in viewtopic in the Forum module. It either doesn't show up, shows up with the option to vote, or shows up with the vote results.

PHP-side
The subtemplate takes normal template variables, so you can assign them as normal. To specify a subtemplate, you merely call on it as you would a normal template file.

 Код:  
if ( $poll_exists )
{
   if ( $user_voted)
   {
      $template->set_filenames(array(
         'pollbox' => 'viewtopic_poll_result.tpl')
      );
   }
   else
   {
      $template->set_filenames(array(
         'pollbox' => 'viewtopic_poll_ballot.tpl')
      );
   }
   $template->assign_var('POLL_NAME' => $poll_name); // Fictional example
   for ($i = 0; $i < count($poll_options); $i++ )
   {
      $template->assign_block_vars('poll_option',array(
            'OPTION_NAME' => $poll_options[$i]) ); // Another fictional example
   }
   $template->assign_var_from_handle('POLL_DISPLAY', 'pollbox');
}


The variables you want displayed in the subtemplate must be assigned before you call the assign_var_from_handle()

Template-side
Just display it like a normal variable.

 Код:  
{POLL_DISPLAY}


You can't assign loop variables from handle. The key in the set_filenames() call (ie, 'pollbox') must be identical to the value in the assign_var_from_handle() call.

That about wraps up this tutorial. I hope it sheds some light on the template engine.

References
 


Часовой пояс: GMT + 3

Кто онлайн
Кто онлайн
Кто онлайн Всего зарегистрированных пользователей: 405
Последний зарегистрированный пользователь: MugenEi
Сейчас посетителей на сайте: 78, из них зарегистрированных: 0, скрытых: 0, гостей: 63, ботов: 15
Больше всего посетителей (302) здесь было Июль 27 2023, 12:54
Зарегистрированные пользователи: нет
Боты : AhrefsBot (15)
Легенда: Админ, Зам.админа, ViP, Спамеры
Эти данные основаны на активности пользователей за последние пять минут

Вход
Вход
Пользователь:    Пароль:     Автоматически входить при каждом посещении     

Powered by R3-Born² © 2024
Все логотипы и торговые марки являются собственностью их законных владельцев.
Правила пользования | Полис Секретности

Valid XHTML 1.0 Transitional SPECIALIST® Online Certified PHP Specialist Valid CSS!