Add function to render a latte file

mrcosgrove
Member | 11
+
0
-

I am trying to add a function to latte that includes a latte file , something like:

$this->template->addFunction(‘hello’, function ($hellotext) {
return “{include ‘test.latte’, hello: $hellotext}”;
 });

this code will just render the text as is instead of including the file. Is there a way get this code to actually include the file and render it?

mystik
Member | 296
+
+1
-

Templates are compiled before they are executed so this is not possible I think. What are you trying to achieve? Why dont you include file directly instead of calling funxtion? Maybe there is another way how to do it.

nightfish
Member | 475
+
0
-

@mrcosgrove Well, I suppose you could try to call Latte this way:

$this->template->addFunction('hello', function ($hellotext) {
    $latte = new Latte\Engine; // or use latteFactory
    $latte->setTempDirectory('/path/to/tempdir');

    return $latte->renderToString('test.latte', ['hello' => $hellotext]);
});

You can also read templates from strings – see docs

Last edited by nightfish (2022-12-17 20:28)

mystik
Member | 296
+
+2
-

@nightfish But this would lost caller context (variables, filters, …) entirely. So it will not work exactly as include. Hard to tell without more info if that is a problem.