What do the {% block %} tags do, exactly?

I’ve read the docs but I didn’t seem to find a proper explanation about them. What do the block tags do? What are they for?

For example: in the docs it says that a theme’s default.md should look something like this:

{% extends 'partials/base.html.twig' %}

{% block content %}
    {{ page.content }}
{% endblock %} 

So what does {% block content %} do here, exactly? Couldn’t I just use the {{ page.content }} without the block tags?

Another example. In the Agency theme there’s this:

{% block body %}
   <div class="container">
   </div>
   {% block content %},{% endblock %}
{% endblock %}

{% block footer %}
  {% include 'partials/footer.html.twig' %}
{% endblock %} 

Again, are both the {% block body %} and {% block footer %}really necessary here? Wouldn’t it work exactly the same without them?

I feel like an idiot for not understanding this. It seems simple enough but I just don’t get it… Apparently they’re somehow related to the connections between base files and the partials, I guess? I’d appreciate a quick explanation about the logic.

That Twig template file (default.html.twig) extends partials/base.html.twig. If you look in that file, you can see the blocks are defined there, and put in the appropriate HTML structure position.

What happens is that when using that Twig template file, the content of the block is put in the place where the block is defined in the extended twig.

It “overrides” it, and provides some custom / specialized code. You cannot directly put output in a Twig file that extends another one, you can try but you’ll get an error.

It’s a Twig thing, you can see the details here: http://twig.sensiolabs.org/doc/tags/extends.html

Oooh, right. I think I get it now. Thanks for the help!

I think what confused me was that base.html.twig is in the /partials folder, even though it’s the actual file that the partials override. (Isn’t that the opposite of a partial?) Then there are things like default.html.twig and modular.html.twig, which are partials that override base.html.twig, but are not in the /partials folder but in the folder above. That confused the heck out of me.

I strongly recommend reading this for a good summary of how to use Twig:

http://twig.sensiolabs.org/doc/templates.html

Thanks! Ok, that cleared it all up. I should’ve read that first.