Search code examples
phpsymfonysymfony-3.2

How to move Bundle/Resources folder to a subfolder in Symfony?


I'd like to structure a Symfony3 Bundle into submodules.

For this I would like to move the Bundle/Resources folder (with views, config and public) along with the controller classes into a subfolder.

Example with a DemoBundle and the Messages module. The directory should be like this:

+ DemoBundle
    + Directory
    + Posts
    + Messages
       + Controller
           + MessageController.php
       + Resources
           + config
           + public
           + views
               + listing.html.twig

I could move the Controller by making an entry to the routing.yml file like this:

demo-messages:
    resource: "@DemoBundle/Messages/Controller/"
    type:     annotation
    prefix:   /

The Controller now looks like this:

class MessageController extends Controller {
    /**
     * @Route("/messsages", name="Message")
     */
    public function listingAction(Request $request) {
        return $this->render('listing.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
        ]);
    }
}

When I now navigate to this route, I get an error: "Unable to find template". The error says it is still looking in /demo/Resources/views instead of /demo/messages/Resources/views.

Question: Can I somehow tell symfony to look in the folder /demo/messages/Resources/views? Is that possible at all? Or is my template addressing in $this->render(...) wrong?


So far tried the following versions for the template reference:

return $this->render('messages/listing.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            ]);

Effect: Error: Template not found

~~~

return $this->render('@DemoBundle/Messages/Resources/views/listing.html.twig', [
            'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
        ]);

Works!


The reason I chose this structure over a Bundle for each submodule is that i would like to encapsulate the user interface in this Bundle while i'd like to organize the admin interface in the AdminBundle.


Solution

  • Cerads solution with namespaced template references helped. The following code worked:

    return $this->render('@DemoBundle/Messages/Resources/views/listing.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            ]);
    

    Drawbacks with this workaround are that the short hand template reference is not possible any more and that the copying of the assets (CSS, JS, etc.) doesn't work with php bin/console assets:install