Extending a Symfony parent Twig block in child view’s block with parent() call easy, useful and DRY

Twig blocks are like methods in a class.  If the Twig container is a class, Twig blocks are methods.  So you can call on a parent Twig view and extend the parent just like a function using the “parent()” function like below within the dynamic content tags, which are a pair of squiggly brackets.  Here’s an example of how you can extend a parent’s block from a child view.

{% extends “MainBundle::Base:main.html.twig” %}

{% block Css %}
   {{ parent() }}
   <link rel="stylesheet" href="addUniqueStylesheetForThisView.css">
   <link rel="stylesheet" href="addAnotherStylesheet.css">
{% endblock %}

Without using “parent()” above, this child “Css” block will completely override the parent’s Css block.  As the title states, this is easy, useful and helps your code stay “DRY” – Don’t Repeat Yourself.

Is your company still not on a PHP framework?  Do you feel you need to modernize your company’s web, code, systems, databases and infrastructure?  Consider a “Business Systems Audit” by Belchamber Business Consultants, they will help you cut costs, improve your web development workflow, all while improving the stability of your code and systems and making your entire organization more effective.  PHP Symfony experts can help shed light on your I.T. and/or web development department.  Maybe it’s time to shake things up?

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *