Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending all templates in a bundle from the controller

Tags:

twig

symfony

I have a lot of templates in a bundle and they all extend the same layout.html.twig. Rather than have to define:

{% extends 'MyBundle::layout.html.twig' %}

at the top of every template, is there a way to do configure this?

I suspect that I would need to create a pre- or postExecute()-like method based on an event listener that extended the template before rendering.

like image 292
nurikabe Avatar asked Nov 04 '22 10:11

nurikabe


1 Answers

This is not a good idea, because not every template has to extend a layout: there are some “system” templates like form_div_layout.html.twig that are not meant to extend anything. Besides, not every template you write has to extend a layout; you'll encounter a lot of use cases for small embeddable templates to reference from other templates.

If you will try to force a layout on each template, you'll have to write some logic to exclude “system” and embeddable templates so that they don't extend anything, and you'll have to do the same for your layout template too, so that it doesn't extend itself infinitely. In this case you'll reverse the problem: instead of defining explicitly which layout to extend in each template, you'll have to explicitly state which templates should not extend your layout. This will get very messy very fast.

To grasp this idea more completely, you need to know that, behind the scenes, templates are really just PHP classes. Does it make sense to you to make a particular class the parent for every other classes, and then explicitly state which classes should not extend this parent?

But if I haven't convinced you not to go this way, there is a Twig setting which lets you set the base template class for all templates:

twig:
    base_template_class: Your\Layout\ClassName\Here

You can extend \Twig_Template or implement \Twig_TemplateInterface and have some “fun” for several hours, after which I hope you'll be convinced to abandon this idea whatsoever. Good luck. :)

like image 147
Elnur Abdurrakhimov Avatar answered Nov 15 '22 09:11

Elnur Abdurrakhimov