MiChAeLoKGB MiChAeLoKGB - 3 months ago 20
PHP Question

Latte - call function in TPL (ideally with parameter) instead of variable

I decided to rewrite an older website that I made years ago and use templating system. I decided to use Latte, as its generating PHP files, which makes it really fast compared to systems that parse tpl every time. But I was not able to figure out, how to call a function with latte and get its result.

I am used to our custom company TPL system which can call any function and even pass parameters to it just by calling

{function_name.param}
or use function constants with
{function::param}
.

Is something like this possible purely in Latte (I am not using Nette or any other framework)? I do not want to call every single function in PHP and add it to array of parameters that TPL has to its disposal. That just makes it slower (yep I know I could use ifs in there and then ifs in TPL, but that's also an useless code duplication).

I want it to be able to call a function within class that's rendering the TPL (or its parent classes OFC) and return its output when I need it (if I even do need it), so I can avoid unnecessary calls to functions when initializing parameters for TPL parsing.

I tried to google quite a lot, but I didn't find anything useful.

I should also mention, that I am not going to use any framework at all, except Latte with Tracy and Tester for automatic testing. I do not want to use Nette or Symfony 2 etc. as the site is not that big and using whole framework would just make it even more complicated than it needs to be.

Thanks.

.

Ps.: Could somebody create tag for Latte?

Answer

You can simply call any php function this way:

{? echo 'hello'}

or in newer versions of Latte:

{php echo 'hello'}

Also, you can pass instances of Nette\Utils\Html (small lib separated from framework, full of great tools even for small apps) which will be directly rendered.

Template sample including your later questions:

{php
    // You can instantiate needed classes in one synoptical block
    // in the head of template file or reather instantiate them
    // outside of template and pass them as template variables
    $a = new ClassA();
    $b = new ClassB();
}

<div>{$a->someFunction()}</div>
<div>
    {* Or you can instantiate class inplace this way,
       but I wouldn't recommend it. BTW: This is Latte comment.
    *}
    {php (new ClassC())->otherFunction()}
</div>