Using base.html.twig as default layout in Symfony2 in dry way

I have a very simple problem: I have a Symfony2 application and it does not use the base layout file, base.html.twig. What does it take for your application to use this layout? It looks like he should just use it automatically.

Edit: I found that if I put {% extends "::base.html.twig" %}

at the start of any layout file and then put in {% block body %}

and {% endblock %}

around my content, it will use base.html.twig

. However, I have so far only figured out how to do this for each file. If you have to do this, include it in every template you want to use it for, that would be surprisingly silly, and I can't imagine this is the case, given how much DRY is applied throughout Symfony.

So, a more specific version of my question: How can I get Symfony to use base.html.twig globally, in a dry way?


source to share

5 answers

It looks like I found the answer to my own question, although I sincerely hope I am wrong. According to this section of the docs , you must include this extends

thing on every page of your template! I just rip on the computer.

Edit: To be clear, the answer to my question is obviously that this is not possible.



First, you need to understand which Twig templates are compiled for the classes. Then imagine that what you are asking is how to ask how to make all your simple PHP classes an extension of the base class without writing extends

to your code. Does this sound like a good idea?



There is a way to do this. This is not recommended, but it is possible.

    base_template_class: Path\To\Base\TemplateClass


Perhaps you may run into problems. Symfony2 also has a template that is not designed to use the base template, so you may need to look into overriding this functionality for system templates.

I would look at the docs as well as this.They both talk about using this feature.



Yes, I raised this issue on github and this is what fabpot had to say

The layout is part of the template and is located there. You should be able to do whatever you want with variables, and if you want to conditionally extend the template look here:

So the bottom line is that we can't do it, or we shouldn't do it, and if we do it, we do it wrong ...



This is not an answer, but a workaround. A good tip is to save the macro in your editor and load it automatically for files twig

. Then when you need it, apply it and you save a lot of keystrokes. It's not DRY for code at all, but it's for your fingers and I prefer to do it instead of modifying the symfony core.

Below is the macro for VIM. Put this in .vimrc

, reload vim and in the file, twig

run @t


autocmd BufNewFile,BufRead *html.twig let @t="ggO{% extends '::base.html.twig' %}\033o{% block body %}\033Go{% endblock %}\033gg"




All Articles