6

Here's a basic example of using nested extends in Twig. I figured this is a probably common use-case. You have a very general _layout.html that contains your common CSS, JS, meta tags, etc.

{# _layout.html #}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>{{title}}</title>
</head>
<body>
  {% block content %}{% endblock %}
</body>
</html>

Then you have a _subpage.html template that shapes the way all your subpages should look (main content area, sidebar, etc).

{# _subpage.html #}
{% extends "_layout" %}

{% block content %}
  <main>
    {% block subpageContent %}{% endblock %}
  </main>

  <aside>
    {% block subpageSidebar %}{% endblock %}
  </aside>
{% endblock %}

Now I extend that _subpage.html in about.html and grab the blocks that belong to the _subpage.html template.

{# about.html #}
{% extends "_subpage" %}
{% set title = "About" %}

{% block subpageContent %}
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestiae cupiditate suscipit, debitis accusantium tenetur impedit, veritatis id placeat, dolor hic temporibus architecto quas atque sunt officiis corrupti voluptatibus expedita. Assumenda!</p>
{% endblock %}

{% block subpageSidebar %}
  <li><a href="#">Subpage Link 1</a></li>
  <li><a href="#">Subpage Link 2</a></li>
  <li><a href="#">Subpage Link 3</a></li>
{% endblock %}

Now I realize you can use nested extends in Twig, but I'm entirely sure if I should. Is this a maintenance nightmare? Does it take a performance hit to do this? What's the best practice for template relationships?

4

I like to have the document skeleton with the head, scripts etc. in a _base.html template and if there's more than one basic page layout (think sidebars etc.) I additionally extend it with _layout-a.html, _layout-b.html, templates. Everything else I use includes for.

The templates are being transpiled down to PHP and cached, so there should not be any measurable performance influence really.

| improve this answer | |
  • Thanks for the feedback! Sounds like it's a pretty common practice and there's virtually no performance hit. Thanks for confirming some suspicions for me. – Aaron Bushnell Feb 19 '16 at 3:47
  • I would say it's actually better for maintenance to make use of inheritance wherever possible, that way you're not repeating portions of the same code across several different layouts (which can lead to bugs). Good to stick with the DRY principle. – Simon East Aug 5 '16 at 12:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.