I search for a way to change the configuration of the Symfony twig bundle in order to register additional twig namespaces.
I tripped over prepend extension but this would just solve the problem half way. When I write code like this:
public function prepend(ContainerBuilder $container) { $bundles = $container->getParameter('kernel.bundles'); if (isset($bundles['TwigBundle'])) { $config = $container->getExtensionConfig('twig')[0]; $paths = ['/path/to/cms' => 'cms']; if (array_key_exists('path', $config)) { $paths = array_merge($config['paths'], $paths); } $config['paths'] = $paths; $container->prependExtensionConfig('twig', $config); } }
This would mean that no other bundle could ever change the twig configuration again:
How to add twig namespaces from inside a bundle without obstructing a way for other bundles to do the same?
Advertisement
Answer
Twig namespaces are an application concern, not a bundle concern.
Registering new namespaces from within the bundle could clash with already defined namespaces by the application that consumes the bundle.
Furthermore, it’s not necessary, because Symfony already auto-crates a namespace for each bundle:
If you install packages/bundles in your application, they may include their own Twig templates (in the
Resources/views/
directory of each bundle). To avoid messing with your own templates, Symfony adds bundle templates under an automatic namespace created after the bundle name.For example, the templates of a bundle called
AcmeFooBundle
are available under theAcmeFoo
namespace. If this bundle includes the template<your-project>/vendor/acmefoo-bundle/Resources/views/user/profile.html.twig
, you can refer to it as@AcmeFoo/user/profile.html.twig
.
You shouldn’t mess with that configuration. Leave it up to the application developer or the framework to deal with it.