In a previous post, I discussed how to use standard PHP functions within eZ Publish Templates. This article demonstrates how to use custom functions instead using custom Template Operators.
What is a Template Operator?
Template operators are the standard tags you use in the templates of eZ Publish, for example, the following are all template operators (a complete list can be found here):
{$node|attribute(show)}
{currentdate()|datetime( ‘my_format’ )} (this is two, current date is a template operator and so it datetime)
Why create your own?
My previous post briefly touched on how the Wrap Operator could be used for a similar purpose. However, as I suggested, Template Operators are better as they make sure your template files much cleaner and easier to understand. They also make it easier to separate out your functionality so your functions for say, data extraction can be separated from your formatting functions. Here is an example of how custom Template Operator and the the Wrap Operator alternative are written in templates. The function is for pulling out a set number of winners for a competition:
Wrap Operator: {wrap_user_func("pick_winner", array($node,4))}
Implementing Template Operators
When creating template operators, eZ Publish can do some of the work for you. If you go to your setup tab there is an option in the left menu called “RAD”, click on it and you can start a wizard to either create a template operator or to create a new datatype (see the screenshot below):
Once you have selected “Template operator Wizard”, you will be given a set of options over a couple of steps for creating your Template Operator. Due to permissions set within eZ Publish, files within extension directories are usually set so that eZ Publish cannot write to them. For this reason, once your Template Operator is created, eZ will give you the source code for the Template Operator rather than store the file for you. With the limitation of the wizard out the way, let’s create an example Template Operator. As our example, let’s make a Template Operator which will multiple each element of an integer array by a chosen number. Not overly useful, but it will show you what you need to know when you build your own.
Stage 1: Setting the Stage - The first stage in the wizard will look as follows. There are no options but it will just give you information about the RAD Template Operator Wizard:
Stage 2: Basic Function Information – Here we enter in basic information such as the function name and whether input and output is required. The final piece of information tells eZ Publish how parameters will be passed in. I tend to do it sequentially (as the Template Operators are above) however this is up to you. For an example of named parameters have a look at the eZ Fetches which all use this approach
Stage 3: Finalising the Code - Here eZ Publish requests information for documenting the new class which will hold the Template Operator. I’ve added some basic information about the class and updated the Class name. It should be noted that although the file you have created only contains one Template Operator, you can update the code to contain as many as you need to. For this reason, I’ve used a slightly more generic class name and description:
Stage 4: What to do with the Source Code – Luckily, the source code gives us the steps we require to add our new template operator to the site. If you take a look at the code, you will also see the information you entered on the previous step is also included in the code. We’ll continue with this stage after the source code
<?php
/*!
\class ExtraMaths extramaths.php
\ingroup eZTemplateOperators
\brief Handles additional Mathematics functionality within the site.
\version 1.0
\date Sunday 23 May 2010 5:47:58 pm
\author Administrator User
Example:
\code
{$value|array_multiply($input2)|wash}
\endcode
*/
/*
If you want to have autoloading of this operator you should create
a eztemplateautoload.php file and add the following code to it.
The autoload file must be placed somewhere specified in AutoloadPath
under the group TemplateSettings in settings/site.ini
$eZTemplateOperatorArray = array();
$eZTemplateOperatorArray[] = array( ’script’ => ‘extramaths.php’,
‘class’ => ‘ExtraMaths’,
‘operator_names’ => array( ‘array_multiply’ ) );
If your template operator is in an extension, you need to add the following settings:
To extension/YOUREXTENSION/settings/site.ini.append:
—
[TemplateSettings]
ExtensionAutoloadPath[]=YOUREXTENSION
—
To extension/YOUREXTENSION/autoloads/eztemplateautoload.php:
—-
$eZTemplateOperatorArray = array();
$eZTemplateOperatorArray[] = array( ’script’ => ‘extension/YOUEXTENSION/YOURPATH/extramaths.php’,
‘class’ => ‘ExtraMaths’,
‘operator_names’ => array( ‘array_multiply’ ) );
—
Create the files if they don’t exist, and replace YOUREXTENSION and YOURPATH with the correct values.
*/
class ExtraMaths
{
/*!
Constructor, does nothing by default.
*/
function ExtraMaths()
{
}
/*!
\return an array with the template operator name.
*/
function operatorList()
{
return array( ‘array_multiply’ );
}
/*!
\return true to tell the template engine that the parameter list exists per operator type,
this is needed for operator classes that have multiple operators.
*/
function namedParameterPerOperator()
{
return true;
}
/*!
See eZTemplateOperator::namedParameterList
*/
function namedParameterList()
{
return array( ‘array_multiply’ => array( ‘first_param’ => array( ‘type’ => ’string’,
‘required’ => false,
‘default’ => ‘default text’ ),
’second_param’ => array( ‘type’ => ‘integer’,
‘required’ => false,
‘default’ => 0 ) ) );
}
/*!
Executes the PHP function for the operator cleanup and modifies \a $operatorValue.
*/
function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
{
$firstParam = $namedParameters[‘first_param’];
$secondParam = $namedParameters[’second_param’];
// Example code. This code must be modified to do what the operator should do. Currently it only trims text.
switch ( $operatorName )
{
case ‘array_multiply’:
{
trim( $operatorValue );
} break;
}
}
}
?>
<!– STOP: including template: design/admin2/templates/setup/templateoperator_code.tpl (design:setup/templateoperator_code.tpl) –>
Stage 4: What to do with the Source Code (continued) – lets create an extension to store the Template Operator in. To do this, go into the extension directory in the root and then create a new folder. I’m calling mine onequarterenglishmodules (replace onequarterenglish with the name of your site but be wary of using capitals as this can cause issues). Once you have done this create a folder called “autoloads” and move your file into this folder (the path will be extension/onequarterenglish/autoloads/extraMaths.php).
Stage 5: Activating the Extension – For eZ Publish to find the functionality we are adding to the extension, we need to tell it to look for it. The source code we have generated tells us what we need to do to ensure eZ Publish looks for Template Operators within the extension but we also need to make sure the Extension is active. To do this go to the setup tab in the CMS and click on the link in the left column called “extensions”. Once here, check the box next to your extension and then click on “activate”. Once this is done click “Regenerate autoload array for extensions”.
The other task is to create a folder in the root of your extension called “settings”. Within this folder create a file with called “site.ini.append.php”. Below is the code you need to add. Please note you only need to do this step once, after that any other new files you create to store Template Operators, or any new template operators you add to this file, do not require it.
extension/onequarterenglish/settings/site.ini.append.php
/*
[TemplateSettings]
ExtensionAutoloadPath[]=onequarterenglishmodules
*/
?>
Stage 6: Activating the Template Operator – The source code we have generated also tells us to how automatically load the Template Operator for use. In our autoloads directory add a file called “eztemplateautoload.php” and add the following code to it. This will tell eZ Publish to have this function available by default:
extension/onequarterenglish/autoloads/eztemplateautoload.php
Stage 7: Update The Parameters – By default the first parameter is the wrong type. While we’re at it we’ll also change the parameter names. Find the function namedParameterList() in the source code and replace it with the following:
extension/onequarterenglish/autoloads/extramaths.php
Stage 8: Implement The function – We now need to implement the function. Find the function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement ). This is where the Template Operator logic sits. As you can see there is a switch statement which controls which functionality is carried out. In our case, we only have one function but you can easily add more here (just make sure to update the other parts of this file where array_multiply is called in the operatorList and the namedParameterList and also update the eztemplateautoload.php file). It is best to separate the functionality out in to separate functions and call those from within modify but to simplify this example though we won’t do this. Also note that the value to pass back to your template is stored within$operatorValue at the end of the function, nothing is explicitly returned (operatorValue is passed by reference into the function):
extension/onequarterenglish/autoloads/extramaths.php
…
function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters, $placement )
{
$numbers = $namedParameters[‘numbers’];
$multiplier = $namedParameters[‘multiplier’];
switch ( $operatorName )
{
case ‘array_multiply’:
{
$multiplied_numbers = array();
for($i=0;$i<count($numbers);$i++)
{
$multiplied_numbers[$i] = $numbers[$i]*$multiplier;
}
$operatorValue = $multiplied_numbers;//operator value is what is passed back to your template
} break;
}
}
…
?>
Stage 9: Update your Clear the cache – To make sure your updated settings file has taken affect, clear the caches from the setup tab within the CMS, you should now be ready to go!
Stage 10: Use your new template operator – You should now be able to display the new template operator using the standard TemplateOperator format such as the below:
[def $multiplier = 10}
{def $data = array_multiply($numbers,$multiplier)}
Conclusion
Although possibly more complex than it needs to be, the initial creation of Template Operator files can be slightly frustrating. Once you have your base files set up though, adding new operators is extremely easy by updating the right parts of the files we have created here. If you do need to create more than one Template Operator in the same file, make sure to update the modify, namedParameterList and operatorList functions within your main file and also to update the eztemplateautoload.php file. Also make sure that each time you add a new class to your extension (since each Template Operator file is a class), that you update the autoloads extension file as we have done so here.





