Question

I want to create simple star rating function.

I want to to write in Twig template {{ star (9) }} and it should show image (or images) and text rating (9/10).

To pass variables to Twig I use in my controller:

$this->get('twig')->addGlobal('current_url',  $this->currentUrl);

and it works fine.

So in the same controller I use code:

    $function = new \Twig_SimpleFunction('star', function () {
        echo "test";
    });

    $this->get('twig')->addFunction($function);

and in Twig template I use:

{{ star }}

to display it. But it doesn't work at all (no error but also no result).

Question: How should it be written to make it work? And also - is it possible this function this way that I assign some variables to Twig and simple include another Twig file in which stars will be created in loop?

I'm Symfony beginner. I saw How can I create a symfony twig filter? but for me it's to complex at the moment - if possible I don't want to create new services / classes and so on to create simple function.

Was it helpful?

Solution

It's a function, so it should be

{{ star() }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top