registering a latte helper
Notice: This thread is very old.
- pistols
- Member | 26
Hello There,
I think I have found an ideal problem which can be solved with a latte helper
i need to transform a value from this
1
to this
<img src="/images/status_1.png" alt="current status code: 1" />
My problem is that i don't know where in my app should i register this helper, and frankly how :)
I will need this helper in various places in my app, so i would like it to be quite global so i can call it on all the available latte files.
I tried this in my basePresenter
protected function startup()
{
parent::startup();
// custom helper changes status to image
$template->registerHelper('statusToImage', function ($code) {
return "<img src='/images/".$code.".png' alt='Status code: $code'/>";
});
}
but i end up with a Notice, Undefined variable: template
- greeny
- Member | 405
You probably forgot to write
<?php
...
$this->template->registerHelper(...);
...
?>
And I prefer returnig Nette\Utils\Html
over string, so you
don't have to care about escaping or no escaping, example:
<?php
use Nette\Utils\Html;
...
// createTemplate() :
$this->template->registerHelper('statusToImage', function ($code) {
$code = (int)$code;
return Html::el('img', array(
'src' => "/images/$code.png",
'alt' => "Status code: $code",
));
});
?>
Now you can easily use it:
Status: {$status|statusToImage}
And everything is properly escaped.