Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

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

Started by Muut Archive 10 years ago · 5 replies · 432 views
10 years ago

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:

TWIG
{% 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:

TWIG
{% 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.

10 years ago

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

10 years ago

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

10 years ago

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.

10 years ago

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

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1352 9 years ago
Archive · by Muut Archive, 9 years ago
2 935 9 years ago
Archive · by Muut Archive, 9 years ago
2 4064 9 years ago
Archive · by Muut Archive, 9 years ago
1 2949 9 years ago
Archive · by Muut Archive, 9 years ago
3 1119 9 years ago