Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can twig macros return values?

Tags:

php

twig

symfony

I'm trying to write a template in Twig. Inside it I would like it to perform some manipulations on the string data that comes from the controller. In particular, there's a common manipulation (convert from underscore_case to CamelCase) that I'd like to bring out into a separate function. Then later I can use it repeatedly like {% set x = magic(a) ~ magic(b) %}. However I cannot find how to make such a reusable function inside the template itself. There are macros, but those don't seem to be able to return values. Filters are another option that seem to fit the bill, but I can only define those on PHP side.

Can this be done? Or should I do all the advanced string manipulation controller-side? It kinda feels like I'm pulling parts of display logic in there; things that should be in the view.

like image 870
Vilx- Avatar asked Dec 24 '22 04:12

Vilx-


1 Answers

Twig is for outputting data. If you need to "transform" the data you need to do that before you send it to twig or you need to extend twig

Ideally, all the data you send to twig is just variables and arrays that needs the least amount of manipulation on their own.

When you're actually "in" twig, the data processing can be assumed to be "done" and only needs to be outputted in the appropriate places with minimal logic to decide user interface styles.

So revisit your logic and prepare your data better before sending it to twig.

An example for extending a toolkit class that contains our magic methods to do real wizardry.

class CustomToolkit 
{
    public function magic_a($a) 
    {
        return strtolower($a);    }

    public function magic_b($b) 
    {
        return camel_case($b);
    }

    public function magic_tidle($a, $b) 
    {
        return $this->magic_a($a) ~ $this->magic_b($b);
    }
}

Then you add this to your twig instance. I added here a complete instantiation loop. if you have a service provider you can just grab the instance from there and add it to that one.

$twig = new Twig_Environment(new Twig_Loader_Array([
                                                      'html' => $contents
                                                   ]),[
                                                      'auto_reload' => true,
                                                      'debug' => false,
                                                   ]);
$twig->addExtension('toolkit', new CustomToolkit ());
echo $twig->render('html', $values);

Then in your twig code you should be able to do something along the lines of

{% set x = toolkit.magic_tidle("value","value_b") %} 
like image 71
Tschallacka Avatar answered Dec 26 '22 15:12

Tschallacka