Gags
Gags

Reputation: 3829

extend or include multiple instances TWIG

I am using Twig to use as templating engine and i have a common right sidebar that shall be included on all pages.

_base.twig

/* Page HTML header */
    {% block content %} {% endblock %}
/* Page HTML Footer */

index.twig

{% extends "_base.twig" %}
    {% block content %}
         <div id="left-bar">Dynamic Content</div>
         <div id="right-bar">Static Content</div>
    {% endblock %}

about.twig

    {% block content %}
         <div id="left-bar">Dynamic Content</div>
         <div id="right-bar">Static Content</div>
    {% endblock %}

.... so on for many pages.. I want right-bar to be a external page and shall be included every page as content is same always.

I tried using {% extends %} two times but Twig fails as i read that multiple extends are not allowed. So any solutions please.

Upvotes: 2

Views: 2692

Answers (1)

Doc Roms
Doc Roms

Reputation: 3308

With Twig, you have many possibilities for solving your problem :

A/ The parent solution Official doc is here

This solution renders the contents of the parent block in your child Block.

_base.twig

/* Page HTML header */
{% block content %}
    <div id="left-bar">Dynamic Content</div>
    <div id="right-bar">Static Content</div>
{% endblock %}
/* Page HTML Footer */

index.twig

{% extends "_base.twig" %}
{% block content %}
    {{ parent() }}
{% endblock %}

about.twig

{% extends "_base.twig" %}
{% block content %}
    {{ parent() }}
{% endblock %}

other.twig

{% extends "_base.twig" %}
{% block content %}
    <div> If you don't place the parent twig attribute, your menu can't appear and will be overrided</div>
{% endblock %}

B/ The Include Solution Official doc is here

This solution create another block, and call the block in the child block.

_base.twig

/* Page HTML header */
{% block content %}
{% endblock %}
/* Page HTML Footer */

navBar.twig

<div id="left-bar">Dynamic Content</div>
<div id="right-bar">Static Content</div>

index.twig

{% extends "_base.twig" %}
{% block content %}
    {{ include('navBar.twig') }}\]
{% endblock %}

about.twig

{% extends "_base.twig" %}
{% block content %}
    {{ include('navBar.twig') }}
{% endblock %}

If you use the Symfony2 Framework, you can already use the {{ render(controller('')) }} [you can see a sample here] for call a specific controller, himself call a twig view... it's very useful if you want to load a dynamic values in your block, but is less effective than a {{ include('') }}...

For me, the B solution is the best, but both solutions work.

Upvotes: 1

Related Questions