jonbon jonbon - 1 month ago 7
Twig Question

What is the difference between include and block in Twig?

I'm trying to make a bootstrap theme for PhileCMS which uses Twig. Right now I'm working on the menu. I've been searching to find out how to make a page active, and I've been seeing stuff about blocks. Right now my index.html looks something like this

{% include 'header.html' %}
<body>
{% include 'nav.html' %}
<div class="container"}
{{ content }}
{% include 'footer.html' %}


My nav.html looks something like this:

<div class="header clearfix">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation"><a class="{% if app.request.attributes.get('_route') starts with 'home' %}active{% endif %}">Home</a></li>
<li role="presentation"><a class="{% if app.request.attributes.get('_route') starts with 'about' %}active{% endif %}">About</a></li>
<li role="presentation"><a class="{% if app.request.attributes.get('_route') starts with 'contact' %}active{% endif %}">Contact</a></li>
</ul>
</nav>
<h3 class="text-muted">{{ site_title }}</h3>
</div>


Is this proper coding practice, or should I be doing something with blocks? I don't really understand how blocks work.

Answer

You can include whole new template with new blocks. - That is what include do. You inject a template or piece of template defined in other file. So:

{% include 'nav.html' %} 

will inject whatever you have put there and it will replace this whole phrase, this line of code with content of nav.html.

On the other hand when you use {% block body %} for example you override this body block which is inherited from parent template. For example:

If you have block named body in base.html.twig and you will inherit from it like this in another template(let's say blog.html.twig):

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

and then do this:

{% block body %}
   Hello World
{% endblock %}

You will put this hello world inside of body block in base.html.twig.

I hope it's now clear to you.

P.S

If you want to use twig make sure you use twig extension!

Comments