Search code examples
symfonytwigtemplate-inheritance

Include then block on a Twig template


None of the previous questions seem to have any information and about a day and a half of random Google searches turns up nothing.

What I am trying to do is this, I have a base.html.twig template and then a folder with several ui elements (slideshows, navigation menus, etc). The idea being I should be able to do this:

page.html.twig contains

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

{% block content %}

  {% include 'OnMyLemonCommonBundle::features.html.twig' %}

  {% block features %}

    <h2>Featured Articles</h2>

    <li><a href="#">Article 1</a></li>
    <li><a href="#">Article 2</a></li>

  {% endblock %}

{% endblock %}

features.html.twig contains

<div class="row">
  <div class="large-12 columns">
    <div class="row">

      <div class="large-4 small-6 columns">
        {% block features %}{% endblock %}
      </div>

      <div class="large-4 small-6 columns">
        {% block blogs %}{% endblock %}
      </div>

      <div class="large-4 small-12 columns">
        {% block pictures %}{% endblock %}
      </div>

    </div>
  </div>
</div>

The problem is that this will render as follows:

// Content from top of base.html.twig

<div class="row">
  <div class="large-12 columns">
    <div class="row">

      <div class="large-4 small-6 columns">
      </div>

      <div class="large-4 small-6 columns">
      </div>

      <div class="large-4 small-12 columns">
      </div>

    </div>
  </div>
</div>

<h2>Featured Articles</h2>

<li><a href="#">Article 1</a></li>
<li><a href="#">Article 2</a></li>

// Content from bottom of base.html.twig

The question is how would I make this output the following:

// Content from top of base.html.twig

<div class="row">
  <div class="large-12 columns">
    <div class="row">

      <div class="large-4 small-6 columns">

        <h2>Featured Articles</h2>

        <li><a href="#">Article 1</a></li>
        <li><a href="#">Article 2</a></li>

      </div>

      <div class="large-4 small-6 columns">
      </div>

      <div class="large-4 small-12 columns">
      </div>

    </div>
  </div>
</div>

// Content from bottom of base.html.twig

Solution

  • I don't think this is possible, however you can try to use the following

    {% render'bundle:Controller:method' %}
    

    Where you render it like this

    <div class="row">
      <div class="large-12 columns">
        <div class="row">
    
          <div class="large-4 small-6 columns">
              {{ features }}
          </div>
    
          <div class="large-4 small-6 columns">
          </div>
    
          <div class="large-4 small-12 columns">
          </div>
    
        </div>
      </div>
    </div>
    

    I hope this is a solution to your problem