Alexander
Alexander

Reputation: 450

Get data in twig function

Is it bad practice to get data from db in twig function or I should pass it to view in controller?

My function is some kind of interface widget that is used on all pages of site admin section. Then on data change I will have to make changes in all actions. But when I get data directly in extension class our teamlead tells that it's bad MVC.

Upvotes: 0

Views: 554

Answers (2)

Francesco Abeni
Francesco Abeni

Reputation: 4265

Your team leader is right. What you can do is create an action specific to render that widget. I.e create a custom widget, let's say you want to show the number of current active users:

class WidgetController extends Controller
{
    public function usersCountWidgetAction()
    {
        return $this->render('widget/usersCount.html.twig', array(
            "usersCount" => $this->getUsersCount();
        ));
    }

    public function getUsersCount() 
    {
        // call the manager and get the result
    }
}

Now in all your other twigs you can use

{{ render(controller('AppBundle:Widget:usersCountWidget')) }}

Upvotes: 0

Vladimir Djuricic
Vladimir Djuricic

Reputation: 4623

It would be best if you pass it to a view from a controller.

Upvotes: 1

Related Questions