One quarter English
One quarter English

Using standard PHP functions in eZ Publish

April 10th, 2010

Although many standard PHP functions are available in eZ Publish (usually with very different names) there are also a large number which are not available. This seems especially to be the case with the templating functionality for Strings. Common PHP tasks such as str_replace are just not available. There are two simple solutions for this.

Firstly, eZ Publish allows you to add standard PHP functions to your templates by modifying your template.ini.append.php file. This is limited in that you can only use functions with one parameter. For example:

template.ini.append.php

[PHP]
PHPOperatorList[stripslashes]=stripslashes

Your template file

Just use the function as you would any template operator:

{"REMOVE\\ALL\\BACKSLASHES\\FROM\\HERE"|stripslashes()}

The limitation to this method is huge, just how many functions exist in PHP with more than one variable? To get around this you can build your own template operator although it seems more effort than it should be for doing such a simple task. There is an extension available called wrap_operator which allows you to update your ini file with the name of the standard function and it carries out the hard work for you. Although it specifies on the contribution page it works on version 3.8, I have also used it on version 4.1 and 4.3 successfully. Once you’ve downloaded the contribution and installed it to your site, implementing the function then involves specifying it within the custom .ini file called wrap.ini (I had issues adding it to an override of this file so it must go in the extension itself).

The best example of using it is found in the documentation for it in the eZPedia:

extension/wrap_operator/settings/wrap_operator.ini

[PHPFunctions]
PermittedFunctionList[]=str_replace

Your template file

{wrap_php_func("str_replace", array(" ", "-","Hello There!" ) )}

Result

Hello-There!

Although you can also use the wrap operator extension to build custom functions in php, I would suggest using template operators instead. I have written a follow up tutorial for creating your own which can be accessed here. These allow you to group logical functions together in your extensions and you avoid the convoluted function calls you get when you use the wrap_operator extension. Even if you need one function initially, once you have set up your extension it is quick and easy when you need additional functionality in future.

Tags: , ,

Leave a Reply

(will not be published)