Custom PhpFox Template Functions: Simple but Useful
Handling the normal php built-in function inside phpfox template is always cumbersome.Usually we are doing all these stuffs in controller itself and passing to the template for display.
Conventional
Shorten the string:
$longWord = 'The quick brown fox jumped over the lazy dog.'; $shortWord = substr($longWord, 0,20); $this->template()->assign(array('shortWord' => $shortWord));
//output
The quick brown fox
It is always a hassle to repeat this in all controllers where we need such common php built-in functions.
Iconoclastic
As phpfox has its own solution for this , there is hardly any reason to worry about this . Phpfox make use of its own template functions to handle such most needed php built-in functions.
Inspecting the phpfox template, we can find a small piece of code, which does this simple and useful functions .
{$longText|shorten:20} (to shorten the string to some specific characters) The quick brown fox
Quite simple right ?
This method can used for creating our own custom template functions to make things easy.
Let’s investigate what actually happens here. The ‘shorten’ is a phpfox library function, which is used to shorten the words to the given length.
BUILD CUSTOM
Let us take wordwrap as example.
Similar to shorten, if we have a wordwrap template function , it will be easier to split the words directly from the template itself instead of doing the stuff in all controllers wherever it is needed.
Step 1: Template file
{$longText|wordwrap:20} //this is our objective.
We need to take the help of two built-in phpfox libraries for this.
Phpfox template functions make use of phpfox cache template library and phpfox parse library.
Step2: Cache class
/include/library/phpfox/template/cache.class.php
The phpfox built-in _parseModifier() function in template cache class compile custom function into the template it is loaded in.
case 'wordwrap': $sVariable = 'Phpfox::getLib(\'phpfox.parse.output\')->wordwrap(' . $sVariable . $sArg . ')'; break;
The above piece of code will call the parse library and in turns the output class in that.Here in this parse output class we are suppose to write our php wordwrap function.
Step3: Output class
include/library/phpfox/parse/output.class.php
then a simple wordwrap function
public function wordwrap($text,$length=20) { $newText = wordwrap($text, $length, "<br />\n"); return $newText; }
Step4: View the output:
The quick brown fox
jumped over the lazy
dog.
Thats all. Simple but useful right ? . We can create any php functions in the same manner which can be used in template files.