Home » HTML » HTML_Template_Flexy » Manual
An extremely flexible Template core, with multiple engines.
Introduction
Introduction – What HTML_Template_Flexy can do
Introduction
HTML_Template_Flexy started its life as a simplification of HTML_Template_Xipe, However the long term aim of Flexy is to provide a universal Template Base API for Compiling and native PHP type templates.
Flexy currently supports a number of backends (Template Formats), and is designed to be extended to support more, The Key Formats are:
- Standard - A rich Tokenizer driven engine, that uses {variable_placeholders}, attribute based (flexy:foreach="...."), and custom tag <flexy:tojavascript ... To rapidly create PHP code from simple markup. These templates are designed to be editable in WYSIWYG HTML editors, without breaking the tags
- Regex - A classic templating backend, for supporting Smarty, Xipe, or Email type convertion to PHP code.
- Raw - A non compiling backend, that enables you to create templates using PHP, Useful if you intend to redistribute your application and are concerned about compilation
Data can be assigned in two ways with flexy, depending on your preferred style of working.
- Push - you put data into the template engine, using $flexy->setData(), and $flexy->setDataByRef(), this is similar to the way Smarty and other templates work.
- Push/Pull - You provide the outputer with a Data Provider Object, (either a Data Object, or a Controller) that contains the data to display (and objects with methods that can be called). This has the added benefit of making the Variables in the template documentable, using PEAR standards, eg. PHPDoc comments.
With all this Flexibility, it still manages to achieve
- Very Lightweight Simple API, which easy to learn
- In Normal operation very little code is actually loaded (so it's fast)
How does HTML_Template_Flexy differ from other template systems
If you look around you will see there are other template systems available in PHP, they generally fall into two categories, Replacement Systems, or PHP Code builders.
Replacement systems like HTML_Template_IT, FastTemplate, PhpLib Template tend to be slower at doing block and nested block type templates and involve alot of code to add each variable to the template.
Php Code builders like Flexy, Smarty, SimpleTemplate (now HTML_Template_Xipe) tend to be better at more complex templates, and can offer a better approach to extendability. (the long term aim of Flexy is to integrate support for all of these PHP Generator templates into a simple package)
The Standard Compiling Backend uses a Tokenizer, which offers the possiblities of using HTML tags and attributes to provide looping and conditionals, and make dynamic XML_Tree like elements of HTML Forms that can be manipulated in your code. (This conversion is only done once when the template compiles)
Typical use example
Flexy template is normally called from within a Controller Class (in the Model,View,Controller paragam). You just send HTML_Template_Flexy, the name of the template, and the object to output. - any variable you want printing out just has to be set in the object being used to ouput.
Typical usage example for HTML_Template_Flexy
<?php
/* configure the application - probably done elsewhere */
require_once 'HTML/Template/Flexy.php';
require_once 'PEAR.php';
$options = &PEAR::getStaticProperty('HTML_Template_Flexy','options');
$config = parse_ini_file('example.ini',TRUE);
$options = $config['HTML_Template_Flexy'];
/* the page controller class */
class controller_test
{
var $template = "home.html"; // name of template
var $title; // this relates to {title};
var $numbers = array(); // this relates to {numbers} , used with foreach
var $anObject;
var $elements = array(); // this is where the elements are stored
/* start section - deals with posts, get variables etc.*/
function controller_test()
{
$this->start();
$this->output();
}
function start()
{
// the title
$this->title = "Hello World";
// store an object.
$this->anObject = new StdClass;
// assign a value to a member.
$this->anObject->member = 'Object Member';
// if you need form elements - you have to include them.
require_once 'HTML/Template/Flexy/Element.php';
// create an HTML Element for the form element.
$this->elements['input'] = new HTML_Template_Flexy_Element;
// assign a value to it
$this->elements['input']->setValue('Hello');
for ($i = 1;$i< 5;$i++) {
$this->numbers[$i] = "Number $i";
}
}
/* output section - probably best to put this in the default_controller class */
function output() {
$output = new HTML_Template_Flexy();
$output->compile($this->template);
$output->outputObject($this,$this->elements);
}
function someMethod() {
return "<b>Hello From A Method</b>";
}
}
/* the page controller instantaation - probably done with a factory method in your master page controller class */
new controller_test();
?>
Now the example template,
Example Template for HTML_Template_Flexy
//ignore any php tags before this comment
<html>
<head>
<title>{title}</title>
</head>
<body>
<H1>{title}</H1>
<form name="form">
<table>
<tr>
<td>
<?php /* this will be merged with the date in the $element['input'] object*/ ?>
Input Box: <input name="input">
</td>
</tr>
<?php /* note here the use for flexy:foreach as an attribute value */ ?>
<tr flexy:foreach="numbers,number,string">
<td>
<?php /* note here the use for flexy:foreach as an attribute value */ ?>
<a href="mypage.html?id=%7Bnumber%7D">{string}</a>
</td>
</tr>
</table>
<?php /* there is some limited support for array access */ ?>
this is number 2 : {numbers[2]}
<?php /* note that full stops separate object and variables or methods */ ?>
This is a {anObject.member}
<?php /* you can call methods of the object */ ?>
{someMethod()}
<?php /* by default everything is htmlspecialchar escaped use the modifier :h to prevent this. */ ?>
{someMethod():h}
</body>
</html>
<?php /* I've used php for comments here as HTML comments didnt work when generating the
manual .. - you dont have to use them - it has nothing to do with the template engine */ ?>
And the output
Output of example for HTML_Template_Flexy
Hello World Input Box : [Hello ] Number 1 Number 2 Number 3 Number 4 this is number 2 : Number 2 This is a member Variable <B>Hello From A Method</B> Hello From A Method
Configuration Options
Configuration Options – Setting the defaults for HTML_Template_Flexy
Configuration
HTML_Template_Flexy can either be configured globally or on each instance, using an associated array. The easiest way to configure HTML_Template_Flexy is to use ini files (although you may also like to consider the PEAR::Config class, or your own configuration system)
This is a typical configuration file for HTML_Template_Flexy
[HTML_Template_Flexy] templateDir = /home/me/Projects/myapplication/templates compileDir = /home/me/Projects/myapplication/compiled_templates forceCompile = 0 debug = 0 locale = en compiler = Standard
To use this ini file with HTML_Template_Flexy, (and Possibly any other classes that use options like this)
Setting the default options
<?php
$config = parse_ini_file('example.ini',TRUE);
foreach($config as $class=>$values) {
$options = &PEAR::getStaticProperty($class,'options');
$options = $values;
}
?>
Alternatively you can set (or override) the configuration when you instantate the class
Setting the default options
<?php
$options = array(
'templateDir' => '/home/me/Projects/myapplication/templates',
'compileDir' => '/home/me/Projects/myapplication/compiled_templates',
'forceCompile' => 0,
'debug' => 0,
'locale' => 'en',
'compiler' => 'Standard',
);
$template = new HTML_Template_Flexy($options);
?>
Configuration Options
-
templateDirdirectory -
This is the directory where all your templates are located
-
compileDirdirectory -
The directory where the compiled templates will be stored, This directory should be writable by the web server
-
forceCompileboolean -
Normally 0, means that the template will only be compiled once (or if the template file is altered), this is only really usefull if you are developing filters and need to test the result.
-
debuginteger -
The default debugging level (default 0=off), 1= shows some debugging information
-
localestring -
Default is 'en' - english. The language use for reading/writing templates. Currently it is only used in the compiled files filename = eg. originalname.html.en.php
Flexy uses get_text() internally if it is installed, and will replace all strings in a HTML page with the return value of get_text(). - This enables the creation of multilanguage sites with a little less pain.
A file {templatename}.strings.serial is created for each file that is parsed, you can use this with PHP's unserialize function to retrieve an array of all the strings in a file. (for translating), or just use the tool xgettext.
-
compilerstring -
Default is 'Flexy' - The Flexy Tokenizer Driver engine. Other engines available are regex (similar to Xipe's engine), Raw (For plain PHP files with no replacement or compiling) and Standard (depreciated). You can use this field to load your own engines, either based Off the core code, or totally separate..
-
multiSourceboolean -
Default is false - Allow the same template to exist in multiple places (eg. if you have theme's and want to fall back to a default template if the themed version doesnt exist.)
-
templateDirOrderstring -
Default is '' - by default, the first matched template is used, if you have multiple paths, and want the last in the list to be used, then set this to 'reverse'
-
filtersarray|string -
an array or comma separated string of filters ONLY USED BY THE Regex backend, available filters are: BodyOnly (strip everything before and after body tag), Mail (add an extra line break after php tags.), Php (removes php code, not very reliably), SimpleTags (variable, method etc. replacement), XML (replace XML opening tag with echos.)
-
nonHTMLboolean -
default is false - if you use the Flexy compiler, it turns off parsing of HTML, (not heavily tested)
-
allowPHPboolean|string -
default is false - allows php code in templates, normally off to help you reduce the chance of you shooting your self in the foot by forgetting to escape output.. (can be usefull for complex looping), but not normally recommended. setting to true, enables PHP code, setting to 'delete' removes php code. (although it doesnt prevent XSS attacks, so it is only suited to trusted users)
-
flexyIgnoreboolean -
default is false - setting to true, will turn off the conversion of html form elements into HTML_Template_Flexy_Element's
-
numberFormatstring -
default is ",2,'.',','" - this is the piece of code that is appended to the output engine when using the :n modifier, eg. {xxxx:n} is replaced with number_format($t->xxxx,2,'.',','); see the php manual page for number_format the default output would be: 1,200.00
-
url_rewritestring -
when compiling the template flexy can rewrite <img src, <script src, <a href and xul stylesheet urls. The format is "match/original:new/url, match/another/original:new/url" each combo is separated by a comma, and the colon separates the pair. This helps previewing templates without using the engine.
-
compileToStringboolean -
default false - if set to true, the compile will return a string of the compiled template, rather than writing it to the cache file. eg. {object._myvar}
-
privatesboolean -
default false - if set to true, you can access variables prefixed with an underscore (normally private in PEAR's coding standards) eg. {someobject._myprivatevar} and {_myprivate}
-
globalsboolean -
default false - if set to true, you can access php's globals and superglobals, eg. {_POST[myvar]}, {GLOBALS[somevalue]}
-
globalfunctionsboolean -
default false - if set to true, you can access any native php function using the GLOBALS. prefix eg. {GLOBALS.date(#d/m/Y#)} obviously you should trust your template authors, as they can easily run exec() if this is enabled.
-
localestring -
default 'en' - either used to search for language specific templates with {filename}.{locale}.{extension} or in conjunction with the Translation2 language translation toolkit, to set the language used to translate templates to at compile time.
-
Translation2mixed -
default false - you can set this to an array or an existing Translation2 object eg. Translation2 => array('driver'=>'dataobjectsimple', options=>array()));
-
strictboolean -
default false - By default warnings about undefined variabes are hidden, this turns on all PHP warnings during the outputObject calls. Can be usefull for finding bugs hidden by method callbacks.
-
fatalErrorint -
default constant HTML_TEMPLATE_FLEXY_ERROR_DIE - this determines the behaviour when compiling a template fails, normally flexy will die and report the error to the screen, you can change this to HTML_TEMPLATE_FLEXY_ERROR_RETURN, if you want to recieve a PEAR_Error object from compile().
-
pluginsstring|array -
loads plugin classes, (by default from the Plugin folder), these can be used either via {plugin.nameofmethod} or as a modifier {outputstring:dateformat}, default formats are normally collected via configuration options plugin.dateformat, plugin.numberformat.decimals, plugin.numberformat.point, plugin.numberformat.thousands
new HTML_Template_Flexy
new HTML_Template_Flexy – constructor
Synopsis
require_once 'HTML/Template/Flexy.php';
new
HTML_Template_Flexy (
array
$options
)
Description
The Object Constructor accepts options as its arguments. Normally, you do not need to provide any options, as they are set by the PEAR::getStaticPropery(), as described in the configuration.
Parameter
-
array $options- anything you need to change from the default settings
Note
This function can not be called statically.
$flexy->compile()
$flexy->compile() – Converts a template from markup to PHP if required
Synopsis
void $flexy->
compile (
string
$template
)
Description
If necessary it will convert the Template markup into PHP code, and writes it to the compiledTemplate directory adding the {locale}.php to the end of the filename. The Template is only compiled if
- No compiled file exists
- The file modification date of the template is greater than the compiled one
- The forceCompile Flag was set in config or when you created the template object.
It is not normally necessary to set the forceCompile flag, unless you are working on the engine itself.
Parameter
-
string $template- Used in conjuction with the config variable 'templateDir' to locate the template to compile into PHP code.
Return value
string - the location of the compiled file (which could be used
with include) - although it is recommended to use the outputObject methods.
In case compileToString option is set to TRUE, the compiled file
is directly returned as string here.
Note
This function can not be called statically.
Example
Compiling multiple files.
<?php
class controller_test
{
var $masterTemplate = "master.html"
var $template = "home.html"; // name of template
var $title; // page title;
var $numbers = array(); // an array example
/* start section - deals with posts, get variables etc.*/
function controller_test()
{
$this->start();
$this->output();
}
function start()
{
$this->title = "<Hello World>";
for ($i = 1;$i< 5;$i++) {
$this->numbers[$i] = "Number $i";
}
}
/* output section - probably best to put this in the default_controller class */
function output() {
$master = new HTML_Template_Flexy();
$master->compile('some_file_name');
$master->outputObject($this);
}
function outputBody() {
$body = new HTML_Template_Flexy();
$body->compile($this->template);
$body->outputObject($this);
}
}
new controller_test;
?>
Master template example
Page Header Goes here.
{outputBody()}
Page Footer Goes here
Simple ouput example
Page Header Goes here.
some numbers
Number 1
Number 2
Number 3
Number 4
Page Footer Goes here
$flexy->outputObject()
$flexy->outputObject() – Merges a controller object with the template and outputs the result
Synopsis
void $flexy->
outputObject (
object $controllerObject
, array $elements
)
Description
This makes the values of the supplied object (and optionally loads the HTML_Template_Flexy_Elements) available to the template when it is run.
Parameter
-
object $controllerObject- The object you want to use with the template, the values of the object will relate to the $controllerObject->tag will map to {tag} on the template -
array $elements- This is an associative array of form, or dynamic elements names (or id's) which will be merged with the one defined in the template.
Note
This function can not be called statically.
Example
PHP code initiating the template, and outputing it
<?php
class example {
var $tag = ">> hello world";
}
$data = new example;
$elements['test'] = new HTML_Template_Flexy_Element;
$elements['test']->setValue("hello input");
$output = new HTML_Template_Flexy();
$output->compile("hello.html");
$output->outputObject($data,$elements);
?>
The Template with some tags
<B>{tag}</B>
<B>{tag:h}</B>
<INPUT name="test">
Resulting output
<B>>> hello world</B> <B>>> hello world</B> <INPUT name="test" value="hello input">
$flexy->bufferedOutputObject()
$flexy->bufferedOutputObject() – Merges a controller object with the template and returns the result
Synopsis
string $flexy->bufferedOutputObject (
object $controllerObject
, array $elements
)
Description
This maps the values of the supplied object and runs the compiled template, and returns the result.
This can be used in conjuction with PEAR::Cache, or in the example below, with a email template (note this still needs testing.. - the backend should eventually support a native tokenizer for email templates.)
Parameter
-
object $controllerObject- The object you want to use with the template, the values of the object will relate to the $controllerObject->tag will map to {tag} on the template -
array $elements- This is an associative array of form, or dynamic elements names (or id's) which will be merged with the one defined in the template.
Return value
string - the object variables overlayed on the template
Note
This function can not be called statically.
Example
Person DataObject send_password method
<?php
class DataObjects_Person {
var $id;
var $name;
var $password;
var $cleartextPassword;
var $email;
function sendEmail($templateFile,$content) {
$content = is_object($content) ? $content : (object) $content;
foreach(get_object_vars($this) as $k=>$v) {
$content->$k = $v;
}
/* use the regex compiler, as it doesnt parse <tags */
$template = new HTML_Template_Flexy( array(
'compiler' => 'Regex',
'filters' => array('SimpleTags','Mail'),
));
/* compile a text file (email template) */
$template->compile($templateFile);
/* use variables from this object to ouput data. */
$mailtext = $template->bufferedOutputObject($content);
//echo "<PRE>";print_R($mailtext);
/* With the output try and send an email, using a few tricks in Mail_MimeDecode. */
require_once 'Mail/mimeDecode.php';
require_once 'Mail.php';
$decoder = new Mail_mimeDecode($mailtext);
$parts = $decoder->getSendArray();
if (PEAR::isError($parts)) {
return $parts;
}
list($recipents,$headers,$body) = $parts;
$mailOptions = PEAR::getStaticProperty('Mail','options');
$mail = Mail::factory("SMTP",$mailOptions);
return PEAR::isError($mail) ? $mail : $mail->send($recipents,$headers,$body);
}
}
?>
An email template (using the Regex Parser - hence the {t.*})
From: "HTML_Template_Flexy" <html_template_flexy@pear.php.net>
Sender: "HTML_Template_Flexy" <html_template_flexy@pear.php.net>
To: {t.email}
Subject: Here is your new password
Content-Type: text/plain; charset=us-ascii
Dear {t.name}
Your New Password is {t.cleartextPassword}
please use it to log into your bank account :)
The resulting email head and body
From: "HTML_Template_Flexy" <html_template_flexy@pear.php.net>
Sender: "HTML_Template_Flexy" <html_template_flexy@pear.php.net>
To: demo@example.com
Subject: Here is your new password
Content-Type: text/plain; charset=us-ascii
Dear Fred Blobs
Your New Password is 0ab123dcc
please use it to log into your bank account :)
$flexy->getElements()
$flexy->getElements() – Fetch Dynamic HTML Elements from template
Synopsis
array $flexy->
getElements (
)
Description
All Form elements, FORM, INPUT, SELECT and any HTML tag that includes the attribute flexy:dynamic Is converted into HTML_Template_Flexy_Element's and stored serialized in the same folder as the Compiled flexy template.
You can use this array to make changes to these elements or find out what form elements exist on a page.
Note: you should put the modified result as the $elements argument of >outputObject(), you do not however have to fetch the elements to assign them, you can just create blank elements, and merge them.
Return value
array - of Elements contained within the template. (or an empty array if
no form/dynamic elements are used)
Note
This function can not be called statically.
Example
Introspecting a template
<?php
$form = new HTML_Template_Flexy();
$form->compile('some_file_name');
print_r($form->getElements());
?>
template example
<BODY>
<FORM name="XXXX">
<INPUT name="yyy">
<SELECT name="zzz">
<OPTION value="aaaa">AAAAA</OPTION>
</SELECT>
</FORM>
</BODY>
template compiled
<BODY>
<?php echo $this->elements['XXXX']->toHtmlnoClose();?>
<?php echo $this->elements['yyy']->toHtml();?>
<?php echo $this->elements['zzz']->toHtml();?>
</form>
</BODY>
output from the Introspection
Array
(
[XXXX] => html_template_flexy_element Object
(
[tag] => form
[attributes] => Array
(
[name] => XXXX
)
[children] => Array
(
)
[override] =>
[prefix] =>
[suffix] =>
[value] =>
)
[yyy] => html_template_flexy_element Object
(
[tag] => input
[attributes] => Array
(
[name] => yyy
)
[children] => Array
(
)
[override] =>
[prefix] =>
[suffix] =>
[value] =>
)
[zzz] => html_template_flexy_element Object
(
[tag] => select
[attributes] => Array
(
[name] => zzz
)
[children] => Array
(
[0] =>
[1] => html_template_flexy_element Object
(
[tag] => option
[attributes] => Array
(
[value] => aaaa
)
[children] => Array
(
[0] => AAAAA
)
[override] =>
[prefix] =>
[suffix] =>
[value] =>
)
[2] =>
)
[override] =>
[prefix] =>
[suffix] =>
[value] =>
)
)
new HTML_Template_Flexy_Element
new HTML_Template_Flexy_Element – Class constructor
Synopsis
require_once 'HTML/Template/Flexy/Element.php';
new HTML_Template_Flexy_Element (
string $tag = ''
, array $attributes
= null
)
Description
Flexy uses a single lightweight class to represent All HTML Tags, All the variables of the class are public, and you are encouraged to use them. And the methods provide generic assignment and conversion abilities.
To force the toHtml() method to generate XHTML, rather than standard HTML, use $element->setAttributes(array('flexy:xhtml'=>true)); or add flexy:xhtml="true" to the attribute of the element in the template.
Parameter
-
$tag- The name of the HTML Tag eg. img for <img ....
-
$attributes- Associative array of attributes, where key="value" is output when you turn it in toHtml(), If you need to represent a attribute without a value, use TRUE as the value. This also accepts a string in the format "href='/test.jpg' alt='test'", which will be parsed into the attributes array of the object.
Public Properties
-
string
$element->tag -
The name of the html element eg. img for <img...
-
array
$element->attributes -
Attributes for the element
-
array
$element->children -
All the sub elements inside this, can be any object that implements toHtml(), or a string.
-
string
$element->override -
this value of thiswill be output when toHtml() is called, rather than the tags.
-
string|object
$element->prefix -
string or object that implements toHtml() method, and is returned by toHtml() before the tag HTML
-
string|object
$element->suffix -
string or object that implements toHtml() method, and is returned by toHtml() after the tag HTML
-
mixed
$element->value -
when you create an element, that is to be merged later with a full definition, you can assign the value here, and during toHtml(), the toValue() method will be called and select options, checkboxes and input values will be correctly filled in.
Throws
throws no exceptions thrown
Note
This function can not be called statically.
Example
Using an element to change a template.
<?php
$form = new HTML_Template_Flexy();
$form->compile('some_file_name');
// create an instance (note you dont have to specify any details..)
$elements['test'] = new HTML_Template_Flexy_Element;
// change an attribute
$elements['test']->attributes['class'] = 'bold';
// sets the value
$elements['test']->setValue('Fred');
// wrap it with something
$elements['test']->prefix = '******';
$elements['test']->suffix = '!!!!!!';
// for the different types of elements:
$elements['test_textarea'] = new HTML_Template_Flexy_Element;
$elements['test_textarea']->setValue('Blogs');
// select options
$elements['test_select'] = new HTML_Template_Flexy_Element;
$elements['test_select']->setOptions( array(
'123' => 'a select option',
'1234' => 'another select option'
));
$elements['test_select']->setValue('1234');
// checkboxes
$elements['test_checkbox'] = new HTML_Template_Flexy_Element;
$elements['test_checkbox']->setValue(1);
$elements['test_checkbox']->setAttributes(array('flexy:xhtml'=>true));
// array type checkboxes..
$elements['test_checkbox_array[]'] = new HTML_Template_Flexy_Element;
$elements['test_checkbox_array[]']->setValue(array(1,2));
// radio buttons
$elements['test_radio'] = new HTML_Template_Flexy_Element;
$elements['test_radio']->setValue('yes');
$form->outputObject(new StdClass, $elements);
// in the example below, the new data you have added is to the existing attributes
?>
template example
<body>
<form name="xxxx">
<input name="test" length="12">
<textarea name="test_textarea"></textarea>
<select name="test_select"></select>
<input name="test_checkbox" type="checkbox" value="1">
<input name="test_checkbox_array[]" type="checkbox" value="1" />1<br />
<input name="test_checkbox_array[]" type="checkbox" value="2" />2<br />
<input name="test_checkbox_array[]" type="checkbox" value="3" />3<br />
<input name="test_radio" type="radio" id="yes" value="yes" />yes<br />
<input name="test_radio" type="radio" id="no" value="no" />no<br />
</form>
</body>
output from the Template
<body>
<form name="xxxx">
******<input name="test" length="12" class="bold" value="fred">!!!!!!
<textarea name="test_textarea">blogs</textarea>
<select name="test_select">
<option value="123">a selection option</option>
<option value="1234" selected>another selection option</option>
</select>
<input name="test_checkbox" type="checkbox" value="1" checked="checked" />
<input name="test_checkbox_array[]" type="checkbox" value="1" checked>1<br />
<input name="test_checkbox_array[]" type="checkbox" value="2" checked>2<br />
<input name="test_checkbox_array[]" type="checkbox" value="3">3<br />
<input name="test_radio" type="radio" id="yes" value="yes" checked>yes<br />
<input name="test_radio" type="radio" id="no" value="no">no<br />
</form>
</body>
$element->setValue()
$element->setValue() – Utility function to set or store values from common tag types.
Synopsis
$element->setValue (
mixed $value
)
Description
This is used to set the values of form elements, results depend on the type of element
-
text,password inputs, buttonsFills in the value attribute -
checkboxs / radio buttonsadds a checked tag to the matching element -
textareafills in the text area content -
checkbox with arraysadds checked to the matching elements -
selectsadds selected to the
Parameter
-
$valueThe value to assign a form element, (use arrays for multiple selects or checkbox groups)
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$element->setOptions()
$element->setOptions() – Utility function equivilant to HTML_Select - loadArray **
Synopsis
$element->setOptions (
mixed $array
, boolean $noValue
= false
)
Description
Used with HTML Selects, to fill in the options available
Parameter
-
$arraythe options to appear. -
$noValuedon't use the keys from the array sent as the value= part of the option tag.
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$element->removeAttributes()
$element->removeAttributes() – Removes an attributes
Synopsis
$element->removeAttributes (
mixed $attrs
)
Description
use this to remove attributes from the tag when the element is rendered, It may be easier to access the attributes array directly and assign the value to false.
Parameter
-
$attributesname or array of names to remove from tag
Throws
throws
Note
This function can not be called statically.
$element->setAttributes()
$element->setAttributes() – Sets the HTML attributes
Synopsis
require_once 'Flexy/Element.php';
HTML_Template_Flexy_Element::setAttributes (
mixed $attributes
)
Description
Can be used to set attribute values, It is easier to set the attributes directly using the public attributes property.
Parameter
-
$attributesEither a typical HTML attribute string or an associative array
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$element->toHtml
$element->toHtml – Output HTML and children
Synopsis
string $element->toHtml (
)
Description
returns the HTML to represent the object. If you wish to implement your own element, you only need to implement this method, and assign it to the element array..
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$element->toHtmlnoClose()
$element->toHtmlnoClose() – Output Open Tag and any children and not Child tag (designed for use with <form + hidden elements>
Synopsis
string $element->toHtmlnoClose (
)
Description
Used by the template to represent form tags, which only the opening tag are rendered dynamically (so, all tags inside the tag are not forced to be dynamic).
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$factory->freeze()
$factory->freeze() – freeze - freeze's an element. - just copies the value to the override.
Synopsis
require_once 'Flexy/Factory.php';
array HTML_Template_Flexy_Factory::freeze (
array $array
)
Description
this probably needs more thought.. - it would probably need to merge the full tag info with types, to be usefull..
$ar = HTML_Element_Factory::freeze($ar);
Parameter
-
$array(return by refernce key(tag name) => HTML_Template_Flexy_Element
Return value
return Array of HTML_Template_Flexy_Elements
Throws
throws no exceptions thrown
Note
Not documented yet.
$factory->fromArray()
$factory->fromArray() – fromArray - builds a set of elements from a key=>value array (eg. DO->toArray()) the second parameter is an optional HTML_Element array to merge it into.
Synopsis
require_once 'Flexy/Factory.php';
array HTML_Template_Flexy_Factory::fromArray (
array $ar
, optional $ret = array()
)
Description
This package is not documented yet.
Parameter
-
$arkey(tag name) => value -
$retarray key(tag name) => HTML_Element
Return value
return Array of HTML_Template_Flexy_Elements
Throws
throws no exceptions thrown
Note
Not documented yet.
$factory->fromArrayPrefixed()
$factory->fromArrayPrefixed() – fromArrayPrefixed - takes a multi dimensional array, and builds the 'xxx[sss][xx]' => value
Synopsis
require_once 'Flexy/Factory.php';
array HTML_Template_Flexy_Factory::fromArrayPrefixed (
array $prefix
, array $ar
, optional $ret = array()
)
Description
This package is not documented yet.
Parameter
-
$prefix -
$ar -
$ret
Return value
return Array of HTML_Template_Flexy_Elements
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$factory->setErrors()
$factory->setErrors() – setErrors - sets the suffix of an element to a value..
Synopsis
require_once 'Flexy/Factory.php';
array HTML_Template_Flexy_Factory::setErrors (
array $ret
, array $set
, string $format = '<span class="error">%s</span>'
)
Description
HTML_Element_Factory::setErrors($elements,array('name','not long enough'));
Parameter
-
$prefix -
$ar -
$ret
Return value
return Array of HTML_Template_Flexy_Element's
Throws
throws no exceptions thrown
Note
This function can not be called statically.
$factory->setRequired()
$factory->setRequired() – setRequired - sets the prefix of an element to a value..
Synopsis
array HTML_Template_Flexy_Factory::setRequired (
array $ret
, array $set
, string $format = '>span class="required"<*>/span<'
)
Description
HTML_Element_Factory::setRequired($elements,array('name',true));
Parameter
-
$prefix -
$ar -
$ret
Return value
return Array of HTML_Template_Flexy_Element's
Throws
throws no exceptions thrown
Note
This function can not be called statically.
{variable}
{variable} – creates PHP code to echo a variable
Synopsis
Usage (
{variable}
, {variable:h}
, {variable:u}
)
Description
creates PHP code to echo a variable, with optional modifier. Modifiers are
- No Modifier - does htmlspecialchars($variable)
- :h - echos without any change - eg. raw
- :u - echos urlencode($variable)
by default variables are assumed to have calling scope, and are prefixed with $t->, however if they are inside a loop (foreach), then the variables created by the loop are added to the scope and the prefix is not added.
Accessing object variables can be done using a dot as separator:
{object.property},
calling methods is identical: {object.method()}.
Example
setting an object variable
$this->a = "hello >>"; $template->outputObject($this);
Outputting the variable
{a}
{a:h}
{a:u}
Compiled template
<?php echo htmlspecialchars($t->a); ?> <?php echo $t->a; ?> <?php echo urlencode($t->a); ?>
Simple ouput example
hello >> hello >> hello+%3E%3
{method(arguments,#quoted arguments#)}
{method(arguments,#quoted arguments#)} – creates a PHP method call, and echos the results
Synopsis
Usage (
{method()}
, {method():h}
, {method():u}
, {object.method()}
, {method(with.a.variable)}
, {method(with.multiple,variables)}
, {method(with.variables,#and strings or literals#)}
)
Description
creates an PHP method call, any with any number of arguments, as variables or literals (quoted in #). the return value is echoed, and passed by a modifier (like variables)
- No Modifier - does htmlspecialchars($variable)
- :h - echos without any change - eg. raw
- :u - echos urlencode($variable)
Example
Including another template
class example_page {
var $masterTemplate = "master.html";
var $bodyTemplate = "body.html";
function ucfirst($string) {
return ucfirst($string);
}
function includeBody() {
$template = new HTML_Template_Flexy();
$template->compile($this->bodyTemplate);
$template->outputObject($this);
}
}
Calling includeBody in template, and ucfirst
{ucfirst(#this is the header#)}
{includeBody():h}
Footer Goes Here.
Compiled template
<?php echo htmlspecialchars($t->ucfirst("this is the header")); ?>
<?php echo $t->includeBody(); ?>
Footer Goes Here.
Output from the code
This is the header Hello World Footer Goes Here.
{foreach:variable,key,value}
{foreach:variable,key,value} – creates a PHP foreach loop
Synopsis
Usage (
{foreach:variable,key,value}
, {foreach:variable,value}
)
Description
creates a foreach loop, needs an {end:} tag. note that the engine will add the variable to the scope, so they will not be prefixed with $t-> when used inside the loop.
Parameter
-
string variable- relates to $object->variable -
string key- creates a variable 'key' in the current scope. -
string value- optionally creates a variable 'value' in the current scope. (as in $key=>$value)
Example
Setting variables for foreach
$this->a = array(
"dog" => "cat",
"fire" => "water"
);
$this->b = array('a','b','c');
$template->outputObject($this);
Foreach in template
{foreach:a,k,v}
k is {k}, and v is {v}
{end:}
{foreach:b,v}
v is {v}
{end:}
Compiled template
<?php if (is_array($t->a)) foreach($t->a as $k => $v) { ?>
k is <?php echo htmlspecialchars($k); ?>, and v is <?php echo htmlspecialchars($v); ?>
<?php } ?>
<?php if (is_array($t->a)) foreach($t->b as $v) { ?>
v is <?php echo htmlspecialchars($v); ?>
<?php } ?>
example output
k is dog, v is cat
k is fire, v is water
v is a
v is b
v is c
{if:variable}
{if:variable} – creates a PHP if statement
Synopsis
Usage (
{if:variable}
, {if:method()}
)
Description
creates an if statement, with the argument as a variable or method. You must close an if statement with an {end:} statement, and you may use {else:} with it.
Example
Setting variables for if
class example {
function showDog() {
return true;
}
function output() {
$this->showStuff = true;
.........
$template->outputObject($this);
}
}
The template
{if:showStuff}Hello{end:}
{if:showDog()}Doggy{end:}
Compiled template
<?php if ($t->showStuff) { ?>Hello<?php } ?>
<?php if ($t->showDog()) { ?>Doggy<?php } ?>
The output
Hello
Doggy
{end:}
{end:} – closes an if or foreach block
Synopsis
Usage (
{end:}
)
Description
adds a closing brace in PHP so that blocks of conditional HTML are shown correctly. You do not need to use {end:} tags if you are using HTML tag attributes like IF="a,b", as the closing HTML tag will indicate that.
Example
Setting variables for if
class example {
function showDog() {
return true;
}
function output() {
$this->showStuff = true;
.........
$template->outputObject($this);
}
}
The template
{if:showStuff}Hello{end:}
{if:showDog()}Doggy{end:}
The compiled template
<?php if ($t->showStuff) { ?>Hello<?php } ?>
<?php if ($t->showDog()) { ?>Doggy<?php } ?>
The output
Hello
Doggy
{else:}
{else:} – adds an PHP else in an if block
Synopsis
Usage (
{else:}
)
Description
adds an else statement in PHP so that blocks of conditional HTML are shown correctly.
Example
Setting variables for if
class example {
function output() {
$this->showStuff = false;
.........
$template->outputObject($this);
}
}
Else in template
{if:showStuff}Hello{else:}World{end:}
Compiled template
<?php if ($t->showStuff) { ?>Hello<?php } else { ?>World<<?php } ?>
The output
World
<FORM NAME="name"
<FORM NAME="name" – configures automatic form elements
Synopsis
Usage (
<FORM NAME="name">
)
Description
By default, all forms are converted to HTML_Template_Flexy_Elements, so they can be altered at runtime.
Example
Using an element to change a template.
<?php
$form = new HTML_Template_Flexy();
$form->compile('some_file_name');
// create an instance (note you dont have to specify any details..)
$elements['theform'] = new HTML_Template_Flexy_Element;
// change an attribute
$elements['theform']->attributes['action'] = 'http://pear.php.net';
//
// for the different types of elements:
$elements['test_textarea'] = new HTML_Template_Flexy_Element;
$elements['test_textarea']->setValue('Blogs');
// select options
$elements['test_select'] = new HTML_Template_Flexy_Element;
$elements['test_select']->setOptions( array(
'123' => 'a select option',
'1234' => 'another select option'
));
$elements['test_select']->setValue('1234');
// checkboxes
$elements['test_checkbox'] = new HTML_Template_Flexy_Element;
$elements['test_checkbox']->setValue(1);
// array type checkboxes..
$elements['test_checkbox_array[]'] = new HTML_Template_Flexy_Element;
$elements['test_checkbox_array[]']->setValue(array(1,2));
// radio buttons
$val = 'yes';
$elements['test_radio'] = new HTML_Template_Flexy_Element;
// if you have a default - you may want default to using it..
$elements['test_radio']->setValue($val != 'no' ? $val : 'no');
$form->outputObject(new StdClass, $elements);
// in the example below, the new data you have added is to the existing attributes
?>
template example
<BODY>
<FORM name="theform">
<TEXTAREA name="test_textarea"></TEXTAREA>
<SELECT name="test_select"></SELECT>
<input name="test_checkbox" type="checkbox" value="1">
<input name="test_checkbox_array[]" type="checkbox" value="1">1<BR>
<input name="test_checkbox_array[]" type="checkbox" value="2">2<BR>
<input name="test_checkbox_array[]" type="checkbox" value="3">3<BR>
<!-- you need to use id's -->
<input name="test_radio" type="radio" id="radio_yes" value="yes">yes<BR>
<input name="test_radio" type="radio" id="radio_no" value="no">no<BR>
</FORM>
</BODY>
output from the Template
<BODY>
<FORM name="theform" action="http://pear.php.net">
<TEXTAREA name="test_textarea">Blogs</TEXTAREA>
<SELECT name="test_select">
<option value="123">a selection option</option>
<option value="1234" selected>another selection option</option>
</SELECT>
<input name="test_checkbox" type="checkbox" value="1" checked>
<input name="test_checkbox_array[]" type="checkbox" value="1" checked>1<BR>
<input name="test_checkbox_array[]" type="checkbox" value="2" checked>2<BR>
<input name="test_checkbox_array[]" type="checkbox" value="3">3<BR>
<input name="test_radio" type="radio" value="yes" id="radio_yes" checked>yes<BR>
<input name="test_radio" type="radio" value="no" id="radio_no">no<BR>
</FORM>
</BODY>
<INPUT NAME="name">
<INPUT NAME="name"> – creates PHP variable for input values
Synopsis
Usage (
<INPUT NAME="name">
)
Description
fills in the form with values based on the form name and the tag name. If flexyignore is used, it is left alone (or if the body or form has a flexyignore tag it will be left alone).
Example
Using an element to change a template.
<?php
$form = new HTML_Template_Flexy();
$form->compile('some_file_name');
// create an instance (note you dont have to specify any details..)
$elements['test'] = new HTML_Template_Flexy_Element;
// change an attribute
$elements['test']->attributes['class'] = 'bold';
// sets the value
$elements['test']->setValue('Fred');
// wrap it with something
$elements['test']->prefix = '******';
$elements['test']->suffix = '!!!!!!';
$form->outputObject(new StdClass, $elements);
// in the example below, the new data you have added is to the existing attributes
?>
template example
<BODY>
<FORM name="XXXX" flexy:ignoreonly="yes">
<INPUT name="test" length="12">
</FORM>
</BODY>
compiled template
<BODY>
<FORM name="XXXX">
<?php echo $this->elements['test']->toHtml();?>
</FORM>
</BODY>
output from the Template
<BODY>
<FORM name="XXXX">
******<INPUT name="test" length="12" class="bold" value="Fred">!!!!!!
</FORM>
</BODY>
<TEXTAREA NAME="name">
<TEXTAREA NAME="name"> – creates PHP variable for textarea value
Synopsis
Usage (
<TEXTAREA NAME="name">
)
Description
fills in the form with values based on the form name and the tag name. If flexyignore is used, it is left alone (or if the body or form has a flexyignore tag it will be left alone).
Example
Using an element to change a template.
<?php
$form = new HTML_Template_Flexy();
$form->compile('some_file_name');
// create an instance (note you dont have to specify any details..)
$elements['test'] = new HTML_Template_Flexy_Element;
// change an attribute
$elements['test']->attributes['class'] = 'bold';
// sets the value
$elements['test']->setValue('Fred');
$form->outputObject(new StdClass, $elements);
// in the example below, the new data you have added is to the existing attributes
?>
template example
<BODY>
<FORM name="XXXX" flexy:ignoreonly="yes">
<textarea name="test"></textarea>
</FORM>
</BODY>
compiled template
<BODY>
<FORM name="XXXX">
<?php echo $this->elements['test']->toHtml();?>
</FORM>
</BODY>
output from the Template
<BODY>
<FORM name="XXXX">
<textarea name="test" class="bold">Fred</textarea>
</FORM>
</BODY>
<SELECT NAME="name">
<SELECT NAME="name"> – creates PHP variable and code for select lists
Synopsis
Usage (
<SELECT NAME="name">
)
Description
fills in the select values based on the form name and the tag name and adds code to check if the object variable matches them. If flexyignore is used, it is left alone. If static is set, the currently defined options will be used.
Example
Using an element to change a template.
<?php
$form = new HTML_Template_Flexy();
$form->compile('some_file_name');
// create an instance (note you dont have to specify any details..)
// select options
$elements['test_select'] = new HTML_Template_Flexy_Element;
$elements['test_select']->setOptions( array(
'123' => 'a select option',
'1234' => 'another select option'
));
$elements['test_select']->setValue('1234');
$form->outputObject(new StdClass, $elements);
// in the example below, the new data you have added is to the existing attributes
?>
template example
<BODY>
<FORM name="theform" flexy:ignoreonly="yes">
<SELECT name="test_select"></SELECT>
</FORM>
</BODY>
compiled template
<BODY>
<FORM name="theform">
<?php echo $this->elements['test_select']->toHtml();?>
</FORM>
</BODY>
output from the Template
<BODY>
<FORM name="theform">
<SELECT name="test_select">
<option value="123">a selection option</option>
<option value="1234" selected>another selection option</option>
</SELECT>
</FORM>
</BODY>
flexy:if="variable or method()"
flexy:if="variable or method()" – creates a PHP if conditional tag
Synopsis
Usage (
flexy:if="variable"
, flexy:if="method()"
, flexy:if="object.method()"
)
Description
creates an if condition surrounding the tag that it's included in.
Parameter
-
string variable- relates to $object->variable -
string method- relates to $object->method() -
string object.methodrelates to $object->object->method()
Example
Setting variables for foreach
class output {
function hasTest() {
return false;
}
function run() {
$this->a = true;
$this->message = 'oops'
$template->outputObject($this);
}
}
flexy:if in template
<a href="{baseURL}/somepath.html" flexy:if="a">this is the a link</a>
<a href="{baseURL}/somepath.html" flexy:if="!a">this is not the a link</a>
<b flexy:if="hasTest()">hasTest is true</b>
<b flexy:if="!hasTest()">hasTest is false</b>
<span flexy:if="message" class="error">{message}</span>
Compiled template
<?php if ($t->a) { ?><A HREF="<?php echo htmlspecialchars($t->baseURL); ?>/somepath.html">this is the a link</A><?php } ?>
<?php if (!$t->a) { ?><A HREF="<?php echo htmlspecialchars($t->baseURL); ?>/somepath.html">this is not the a link</A><?php } ?>
<?php if (isset($t) && method_exists($t,'hasTest')) if ($t->hasTest()) { ?><B>hasTest is true</B><?php } ?>
<?php if (isset($t) && method_exists($t,'hasTest')) if (!$t->hasTest()) { ?><B>hasTest is false</B><?php } ?>
<?php if ($t->message) { ?><SPAN CLASS="error"><?php echo htmlspecialchars($t->message); ?></SPAN><?php } ?>
Simple ouput example
this is the a link
hasTest is false
oops
flexy:foreach="variable,key,value"
flexy:foreach="variable,key,value" – creates a PHP foreach loop using a html attribute
Synopsis
Usage (
flexy:foreach="variable,key,value"
, flexy:foreach="variable,value"
)
Description
creates a foreach loop, around the tag and close tag.
Parameter
-
string variable- relates to $object->variable -
string key- creates a variable 'key' in the current scope. -
string value- optionally creates a variable 'value' in the current scope. (as in $key=>$value)
Example
Setting variables for foreach
$this->a = array(
"dog" => "cat",
"fire" => "water"
);
$this->b = array('a','b','c');
$template->outputObject($this);
Foreach in template
<table>
<tr flexy:foreach="a,k,v">
<td>k is {k}, and v is {v}</td>
</tr>
</table>
<table>
<tr flexy:foreach="b,v">
<td>v is {v}</td>
</tr>
</table>
Compiled template
<table>
<?php if (is_array($t->a)) foreach($t->a as $k => $v) { ?><tr>
<td>k is <?php echo htmlspecialchars($t->k); ?>, and v is <?php echo htmlspecialchars($t->v); ?></td>
</tr><?php } ?>
</table>
<table>
<?php if (is_array($t->b)) foreach($t->b as $v) { ?><tr>
<td>v is <?php echo htmlspecialchars($t->v); ?></td>
</tr><?php } ?>
</table>
Simple ouput example
k is dog, v is cat
k is fire, V is water
v is a
v is b
v is c
flexy:start="here"
flexy:start="here" – Start the output, using this tag and its children.
Synopsis
Usage (
flexy:start="here"
)
Description
Tells the generator to start outputing using this tag. This can be useful if you want to edit the template in a editor that expects a head/footer, and you can list the available tags in the comments at the top of the page.
The actual value of the tag is not relivant.
Example
Template with flexy:start
<HTML>
<HEAD></HEAD>
<BODY>
<H1>This is an example</H1>
<FORM name="input" flexy:start="yes">
<INPUT name="hello" flexy:ignore="yes">
</FORM>
</BODY>
</HTML>
Compiled template
<FORM NAME="input">
<INPUT NAME="hello">
</FORM>
flexy:startchildren="here"
flexy:startchildren="here" – Start the output using its children.
Synopsis
Usage (
flexy:startchildren="here"
)
Description
Tells the generator to start outputing using the children of this tag. This can be useful if you want to edit the template in a editor that expects a head/footer, normally adding this to body
The actual value of the tag is not relivant.
Example
Template with flexystartchildren
<HTML>
<HEAD></HEAD>
<BODY flexy:startchildren="here">
<H1>This is an example</H1>
<FORM name="input" flexy:ignoreonly="yes">
<INPUT name="hello" flexy:ignore="yes">
</FORM>
</BODY>
</HTML>
Compiled template
<H1>This is an example</H1>
<FORM NAME="input">
<INPUT NAME="hello">
</FORM>
flexy:ignore="yes"
flexy:ignore="yes" – Prevent Automatic form value replacement
Synopsis
Usage (
flexy:ignore="yes"
)
Description
Tells the generator not to replace form elements with PHP code. Can be used with a Form Tag, or individual elements.
<input>s and<textarea>s withflexy:includeorflexy:ignore: If you are turning off flexy element creation withflexy:ignore="yes", then this is not inherited by included templates, and you need to add that tag to the included template as well.
Example
Template with flexy:ignore
<form name="theform1"> <input name="theinput1"> <input name="theinput2" value="dummy"> </form> <form name="theform2" flexy:ignore> <input name="theinput3" value="dummy"> <input name="theinput4" value="dummy"> </form> <form name="theform3"> <input name="theinput5" value="dummy" flexy:ignore> <input name="theinput6" value="dummy"> </form> <form name="theform4" flexy:ignoreonly="yes"> <input name="theinput7" value="dummy"> <input name="theinput8" value="dummy"> </form>
Compiled template
<?php echo $this->elements['theform1']->toHtmlnoClose();?> <?php echo $this->elements['theinput1']->toHtml();?> <?php echo $this->elements['theinput2']->toHtml();?> </form> <form name="theform2"> <input name="theinput3" value="dummy"> <input name="theinput4" value="dummy"> </form> <?php echo $this->elements['theform3']->toHtmlnoClose();?> <input name="theinput5" value="dummy" flexy:ignore> <?php echo $this->elements['theinput6']->toHtml();?> </form> <form name="theform4"> <?php echo $this->elements['theinput7']->toHtml();?> <?php echo $this->elements['theinput8']->toHtml();?> </form>
flexy:nameuses="variable"
flexy:nameuses="variable" – Use a variable in the name for a flexy form element
Synopsis
Usage (
flexy:nameuses="variable" name="sometag[%s]"
)
Description
If you have a form with multiple input boxes (eg. group members), which are dynamically generated, then this attribute can be used to generate flexy elements based on sprintf'ing the variable value into the name attribute value.
Example
Template with flexy:ignore
<html>
<head>
<title>Example of name Uses</title>
</head>
<body>
<form name="formtest">
<span flexy:foreach="data,key,row">
{key}: <input name="data%s" flexy:nameuses="key" type="hidden" size="10"><br>
</span>
</form>
</body>
</html>
Backend Code Snippet
<?php
$this->data = array();
$elem = array();
$elem['formtest'] = &new HTML_Template_Flexy_Element();
$elem['formtest']->attributes['method'] = 'post';
$elem['formtest']->attributes['action'] = 'test';
for($i = 0; $i < 10; $i++) {
$this->data[$i] = $i;
$elem["data$i"] = new HTML_Template_Flexy_Element();
$elem["data$i"]->attributes['type'] = 'text';
$elem["data$i"]->attributes['size'] = $i;
}
$flexy->outputObject($this, $elem);
?>
Compiled template
<html>
<head>
<title>Example of name Uses</title>
</head>
<body>
<?php echo $this->elements['formtest']->toHtmlnoClose();?>
<?php if ($this->options['strict'] || (is_array($t->data) || is_object($t->data)))
foreach($t->data as $key => $row) {?>
<?php echo htmlspecialchars($key);?>: <?php if (!isset($this->elements[sprintf('data%s',$key)])) $this->elements[sprintf('data%s',$key)]= $this->elements['data%s'];
$this->elements[sprintf('data%s',$key)] = $this->mergeElement($this->elements['data%s'],$this->elements[sprintf('data%s',$key)]);
$this->elements[sprintf('data%s',$key)]->attributes['name'] = sprintf('data%s',$key);
echo $this->elements[sprintf('data%s',$key)]->toHtml();?><br>
<?php }?>
</form>
</body>
</html>
Resulting Output
<html>
<head>
<title>test for PEAR bug#4683</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form name="formtest" method="post" action="test">
0: <input name="data0" type="text" size="0"><br>
1: <input name="data1" type="text" size="1"><br>
2: <input name="data2" type="text" size="2"><br>
3: <input name="data3" type="text" size="3"><br>
4: <input name="data4" type="text" size="4"><br>
5: <input name="data5" type="text" size="5"><br>
6: <input name="data6" type="text" size="6"><br>
7: <input name="data7" type="text" size="7"><br>
8: <input name="data8" type="text" size="8"><br>
9: <input name="data9" type="text" size="9"><br>
</form>
</body>
</html>
<FLEXY:TOJAVASCRIPT JSVAR="PHPVAR"> ...
<FLEXY:TOJAVASCRIPT JSVAR="PHPVAR"> ... – Provides a simple way to pass data from PHP to Javascript
Synopsis
Usage (
<flexy:tojavascript JSVAR="PHPVAR" ...>
)
Description
To reduce the "WTF" effect of magically having javascript code that looks like flexy tags completely broken by the template engine, Flexy deliberately turns the parser OFF when dealing with script contents (see Configuration Options for details of PHP in script tags)
As a result of this, it is not possible to put any flexy tags within blocks of javascript code. the flexy:tojavascript tag solves this in a way that enables javascript to be tested seperatly from the application, and also serves to encourage better coding practices. (eg. seperating your code with distinct lines of communication)
This feature depends on PEAR's HTML_Javascript Library
Example
A template with javascript and flexy:tojavasscript
<?php
<html><head>
<title>Example</title>
<flexy:toJavascript
flexy:prefix="test_abc_"
abcg="xyz"
abcd="xyz"
srcXxx="xyz"
>
<!--
We can use the inner contents for testing the template in a browser.
The template will remove these contents when it is compiled.
-->
<script type="text/javascript">
var test_abc_abcg = '123';
var test_abc_abcd = '123';
var test_abc_srcXxx = '123';
</script>
</flexy:toJavascript>
<flexy:toJavascript abcg="xyz">
<script type="text/javascript">
var xyz = '123';
</script>
</flexy:toJavascript>
<body>
<p>Example of flexy:toJavascript with default values.</p>
</body></html>
?>
compiled template
<html><head>
<title>Example</title>
<?php require_once 'HTML/Javascript/Convert.php';?>
<script type='text/javascript'>
<?php $__tmp = HTML_Javascript_Convert::convertVar($t->xyz,'test_abc_abcg',true);
echo (is_a($__tmp,"PEAR_Error")) ? ("<pre>".print_r($__tmp,true)."</pre>") : $__tmp;?>
<?php $__tmp = HTML_Javascript_Convert::convertVar($t->xyz,'test_abc_abcd',true);
echo (is_a($__tmp,"PEAR_Error")) ? ("<pre>".print_r($__tmp,true)."</pre>") : $__tmp;?>
<?php $__tmp = HTML_Javascript_Convert::convertVar($t->xyz,'test_abc_srcXxx',true);
echo (is_a($__tmp,"PEAR_Error")) ? ("<pre>".print_r($__tmp,true)."</pre>") : $__tmp;?>
</script>
?php require_once 'HTML/Javascript/Convert.php';?>
<script type='text/javascript'>
<?php $__tmp = HTML_Javascript_Convert::convertVar($t->xyz,'abcg',true);
echo (is_a($__tmp,"PEAR_Error")) ? ("<pre>".print_r($__tmp,true)."</pre>") : $__tmp;?>
</script>
<body>
<p>Example of flexy:toJavascript with default values.</p>
</body></html>
output from the Template (with no values set)
<html><head> <title>Example</title> <script type='text/javascript'> test_abc_abcg = null; test_abc_abcd = null; test_abc_srcXxx = null; </script> <script type='text/javascript'> abcg = null; </script> <body> <p>Example of flexy:toJavascript with default values.</p> </body></html>