George Gkirtsou George Gkirtsou - 7 months ago 33
PHP Question

Symfony2 Override part of template from third-party bundle

I am using SonataAdminBundle for my project and I would like to override a block.

If I create a template in

app/Resources/views/SonataAdminBundle/views/standard_layout.html.twig
clear the cache and do this:

{% extends 'SonataAdminBundle::standard_layout.html.twig' %}

{% block theBlockIWantToOverride %}
{% endblock %}


I get a
Maximum function nesting level of '250' reached, aborting!
error.

If I remove the
extends
part it renders a blank page. Instead, I have to copy the entire file contents to this new file and then change the block content. I know this is how Symfony2 works, I just don't know if there is a workaround without having all the code there?

The reason I want to do this is because I use SensioLabsInsight and it's been bugging me about the
raw
twig filter that SonataAdminBundle uses. I know I can just ignore the warning but it feels wrong.

Also, I tried to override the bundle by creating a bundle
php app/console generate:bundle
and then in src/Vendor/AdminBundle/VendorAdminBundle.php I added:

/**
* {@inheritdoc}
*/
public function getParent()
{
return 'SonataAdminBundle';
}


and done the above process, added a
src/Vendor/AdminBundle/Vendor/Resources/views/standard_layout.html.twig
which didn't solve the issue. Again, got the nesting level error.

Answer

The template at app/Resources/views/SonataAdminBundle/views/standard_layout.html.twig is extending SonataAdminBundle::standard_layout.html.twig which is the same file, meaning that it is just extending itself until it dies.

You should copy the contents of the file and change what you need to in that.

Alternatively you could copy the original standard_layout.html.twig and rename it (to standard_base.html.twig for example), then override your blocks in your version of standard_layout.html.twig and then extend your standard_base.html.twig.

Even more alternatively, and better for SonataAdminBundle, you can use a different named template (VendorAdminBundle::standard_layout_override.html.twig for example) as your version of the standard_template.html.twig to extend the original and set it in the config like...

sonata_admin:
    templates:
        layout:  VendorAdminBundle::standard_layout_override.html.twig