Developing a custom helper is straightforward: write a class for it, register it with the HelperLocator, then use it in a template.
To write a helper, extend the Helper class, and implement the __invoke ()
method with whatever parameters you like. Have it return a string that has
been appropriately escaped.
Here is a helper to ROT-13 a string:
namespace My\Helper;
use Qiq\Helper;
class Rot13 extends Helper
{
public function __invoke(string $str) : string
{
return $this->escape->h(str_rot13($str));
}
}
Now that you have the helper class, you will need to register a callable factory
for it in the HelperLocator. (Registering a callable factory allows
the HelperLocator to lazy-load the helper only when it is called.) The
registration key will be the Qiq helper name, or the PHP $this
helper method,
you use for that helper in a template.
$tpl = Template::new(...);
$helperLocator = $tpl->getHelperLocator();
$helperLocator->set(
'rotOneThree',
function () use ($helperLocator) {
return new \My\Helper\Rot13($helperLocator->escape());
}
);
Note that you need to construct Helper classes with the Escape instance already in the HelperLocator.
Now you can use the helper in template, either as Qiq code ...
<p>{{= rotOneThree ('Uryyb Jbeyq!') }}</p>
... or as PHP:
<p><?= $this->rotOneThree('Uryyb Jbeyq!') ?></p>
Either way, the output will be the same:
<p>Hello World!</p>