<ctpp/> home .:. download .:. documentation .:. faq  
o Home
    Download!
    Installation

o Help
    What is the CTPP library?
    How it works?
    Online documentation
    FAQ

o In action
    Projects
    First steps
    HOWTOs..
    Development

o In deveopment
    Schedule
    Credits



Using the CTPP library

Îãëàâëåíèå



Introduction

This document describes basic usage of CTPP in projects written in PHP. It’s recommended that you carefully read the chapter Getting started. The examples in this manual are arranged in order of increasing complexity. So if you’ve skipped some material, and find it difficult to understand the example you are reading, simply go back and review the preceding chapter.

All the files related to the manual are in the directory /examples/php. The manual discusses only the procedural examples. Object-oriented examples are left for the independent study. Typically, they have only minor differences with the examples reviewed here in detail and are easy to understand given the basics of OOP.

Getting started

Any work with extension starts with creating a template object. In procedural style, use the function ctpp_new, in object-oriented use new ctpp:
// Create object
$Template = ctpp_new();
Similar to some other templatie engines, CTPP supports loops, branching, and arithmetic operations in addition to the simple output of data. All parameters are created as "key" => "value" pairs. A key can be any name containing the letters of the Latin alphabet, digits, underscore, or period. A value can be a number, whether integer or floating point, a string, or an array.

Example:
// Correct
$Params = Array("number_one" => 1,
                "number.pi"  => 3.14,
                "text"       => "Hello, World!");

// Wrong
                     // Keys cannot starts from a digit
$WrongParams = Array("1one"       => 1,
                     // Keys cannot contain '-'
                     "number-pi"  => 3.14,
                     // Keys cannot use non-ascii7 characters
                     "òåêñò"      => "Hello, World!");
Every parameter once it’s assigned can be used in the template engine output by passing it to the function ctpp_emit_params or the method emit_params.

Example:
// Pass the data
ctpp_emit_params($Template, $Params);

// Need to insert more parameters? No problem!
ctpp_emit_params($Template, Array("param" => "Additional parameter"));
Use the function ctpp_dump_params for monitoring and debugging output parameters:
// Print output
ctpp_dump_params($Template);
If something goes wrong you can always verify that the input data are indeed those you expect.
You can find the samples archive at the link /examples/php/Getting_Started. An example of the object-oriented usage of the library can be found at the same location.


A Simple Example

In this example we’ll try to output the well known phrase "Hello World!".
In order to do this we need:
1) create the necessary data set
2) load template
3) get output

Let’s watch it in action:
<?php
// Parameters
$Params = Array("hello" => "Hello", "who" => "World");

// Create template engine
$Template = ctpp_new();

// Load template
$Bytecode = ctpp_parse_template($Template, "hello.tmpl");

// Print output
ctpp_emit_params($Template, $Params);

// Print output
echo ctpp_output_string($Template, $Bytecode);
?>
That's all.
Now we only need to create a template file and to save it as hello.tmpl.
	<TMPL_var hello>, <TMPL_var who>!
Tarball with examples: /examples/php/Hello_World.


A more complex example

We’ve just learned how to output simple data from a template. In this section we’ll learn how to use conditions inside a template. Let’s imagine that we are building a site, where the user’s age is verified. In classic PHP we could use a construct like this:
<?php
$Age = _GET['age'];

if ($Age < 18)
{
	echo "Children under 18 use the kids sections of the site!";
}
else
{
	echo "For adults – anything you want!";
}
?>
Clearly a case as simple as this can be easily coded in PHP itself. But if you have many pages that depend on the user’s age it may be more convenient to move the condition into the template code.

Here you go! The comparison moves into the template.
	<TMPL_if (age < 18)>
		You are younger than 18!
	<TMPL_else>
		You are older than 18!
	</TMPL_if>
What if we have several conditions? The expression is little bit complex:
	<TMPL_if (age < 7 || age > 18)>
		Howdy!
	<TMPL_else>
		Only for school age kids!
	</TMPL_if>
In addition to logic operations, CTPP supports combinations of arithmetic and logic. You can find the complete description in the help section "Arithmetic and logic expressions".

If you need, you can test several conditions sequentially:
	<TMPL_if (forum.posts < 100)>
		Newbie
	<TMPL_elsif (forum.posts < 300)>
		Participant
	<TMPL_elsif (forum.posts < 500)>
		ÀActive participant
	<TMPL_elsif (forum.posts < 1000)>
		Veteran
	<TMPL_elsif (forum.posts < 2000)>
		Senior
	<TMPL_elsif (forum.posts < 5000)>
		Flooder ;)
	<TMPL_else>
		Forum Guru
	</TMPL_if>
The conditions are tested in sequence until a match is found. If none is found, the <TMPL_else> branch is executed. In the absence of an ELSE clause the output will be nothing.
Branching works very simply. In fact, we take the data and load it into the template.
<?php

$Age   = $_GET['age']   * 1;
$Posts = $_GET['posts'] * 1;
// Parameters
$Params = Array("age" => $Age, "forum.posts" => $Posts);

// Create template engine
$Template = ctpp_new();

// Load template
$Bytecode = ctpp_parse_template($Template, "branches.tmpl");

// Print output
ctpp_emit_params($Template, $Params);

// Print output
echo ctpp_output_string($Template, $Bytecode);
?>
The samples archive is in /examples/php/Branches.


Loops and functions

That can’t be all we can do... fortunately, it isn’t. Now that we’ve learned to output simple variables, it’s time to explore what else CTPP can do. This section is devoted to loops and built-in functions.

A loop in CTPP is a number of iterations over a data structure. In PHP terms, the data structure is a simple array of arrays:
<?php
$LoopBody = Array( Array("id" => 1, "iteration" => "first"),
                   Array("id" => 2, "iteration" => "âòîðàÿ"),
                   Array("id" => 3, "iteration" => "third"),
                   Array("id" => 3, "iteration" => "fourth") );
?>
In order to move this structure to the template we need an instruction like this:
	<TMPL_loop loop_body>
		ID: <TMPL_var id>, iteration: <TMPL_var iteration>
	</TMPL_loop>
What should we do if we want to have more than one loop on a page? That’s why we use loop names. We specify the name in the template: <TMPL_loop èìÿ_öèêëà>, and in the code we use the parameter key:
<?php
	// Print output
	ctpp_emit_params($Template, Array(("loop_body" => $LoopBody) );
?>
This way we can easily create loops inside loops. The only limit for the number of nested loops is the developer’s imagination:
  • __FIRST__ - is set to "1" during the first iteration of the loop. Not defined in all other cases.
  • __LAST__ - contains the number of the last iteration of the loop during the last iteration. Not defined in all other cases.
  • __INNER__ - contains the number of the iteration from the second to the penultimate. Not defined in all other cases.
  • __ODD__ - is set when the number of the iteration is odd. Not defined in all other cases.
  • __COUNTER__ - is defined for all iterations and contains the number of the current iteration. Counting starts at 1.
  • __EVEN__ - is set when the number of the iteration is even. Not defined in all other cases.
  • __SIZE__ - is defined for all iterations of the loop and contains the total number of the iterations.
  • __CONTENT__ - is defined for all iterations and contains the data from the current cell of the array.
Output variables can be local or global. Local variables are defined in the current iteration of the loop. Global variables are visible everywhere within the template. The variables are resolved in the following order: First, a local variable with a given name is searched for. If there is no such variable, a global variable with the same name is searched for next.

The distinction between local and global variables is useful when designing ticker tapes, product lists and other cyclical structures where a part of a string, for example, a URL can be formatted in the same fashion.
Samples: /examples/php/Loops.


Using Include

Often different pages contain the same elements, for example: menus, news tapes, etc. In order to simplify the layout, repeated elements can be moved into template files and the files are then included using the declaration <TMPL_include "èìÿ_ôàéëà">.

Templates can be included in other templates without any modifications to the PHP code, by simply specifying the directories where the files are located. Use the function ctpp_include_dirs:
<?php
	ctpp_include_dirs($Template,
	                  Array("/usr/share/templates", "/home/myproject/tmpl") );
?>


Error handling

If an error has occurred during the processing of a templatizer, FALSE is retuned from the function or the class method. In this case the function ctpp_get_last_error will return an array with the description and the location of the error.
<?php
	// Print HTML
	$OutputHTML = ctpp_output_string($Template, $Bytecode);
	if ($OutputHTML === false)
	{
		$ErrorDescr = ctpp_get_last_error($Template);
		printf("Error 0x%08X: %s\n", $ErrorDescr["error_code"],
		             htmlspecialchars($ErrorDescr["error_str"]));

		printf("File %s: line %d, pos %d\n",
		                                   $ErrorDescr["template_name"],
		                                   $ErrorDescr["line"],
		                                   $ErrorDescr["pos"]);
	}
?>



Copyright © 2003 - 2008 CTPP Dev Team.