David
David

Reputation: 213

Symfony render controller to get data in twig file

I'm a bit new to symfony (3.2.1), and I would like to have a controller for each twig file controlling my views to keep my controllers thin as indicated in Symfony Best Pratcices.

In my page, I call

{% include "my_bundle/user.html.twig" %}

to have a sidebar with all user info, login, etc..

For user.html.twig I would like to have a separate controller, so I created UserController.php.

Seems like the right way to do it, no ?

For now I'm doing a real basic request but can not seem to make it work, though I thought I did everything right.

So src/AppBundle/Controller/UserController.php looks like :

<?php

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class UserController extends Controller
{
    public function UserIdAction(Request $request)
    {   
        $userID = '2';

        return $this->render('my_bundle:user.html.twig', array('userID' => $userID));
    }
}

and app/Resources/views/my_bundle/user.html.twig looks like :

<div id="userSideBar">
    <div class="container">
        {{ render(controller('AppBundle:Controller:UserId')) }}
        <p>{{ userID }}</p>
    </div>
</div>

Doing that I get error :

An exception has been thrown during the rendering of a template ("The _controller value "AppBundle:Controller:UserController" maps to a "AppBundle\Controller\ControllerController" class, but this class was not found. Create this class or check the spelling of the class and its namespace.").

I also tried app/Resources/views/my_bundle/user.html.twig like :

<div id="userSideBar">
    <div class="container">
        {{ render(controller('AppBundle:Controller:UserId', { 'userID': userID })) }}
    </div>
</div>

But then I get error :

Variable "userID" does not exist.

Any idea on where I could be wrong please ?

EDIT :

I may have missed an important part here :

To include the controller, you'll need to refer to it using the standard string syntax for controllers (i.e. bundle:controller:action)

So I changed app/Resources/views/my_bundle/user.html.twig to :

<div id="userSideBar">
    <div class="container">
        {{ render(controller('AppBundle:User:UserId')) }}
    </div>
</div>

But now I get :

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 8388608 bytes)

and server stops running, really confusing.

Upvotes: 1

Views: 3968

Answers (1)

Victor Nazarkiv
Victor Nazarkiv

Reputation: 11

I had trouble likes this. When i try to render controller in twig, PHP STORM was show wrong path. As my template was not in root folder Controller it light me "AdminBundle:Client\Companies:clientsWidget" but I was need change slash "AdminBundle:Client/Companies:clientsWidget"

Upvotes: 0

Related Questions