background

October 8, 2023

Magento 2 AdditionalBlockTemplate

Yireo Blog Post

If you override any PHTML template, the legacy of your theme goes up: More to maintain. Because of this, we should strive for as less code duplication as possible. The Yireo AdditionalBlockTemplate module might offer part of that solution.

Adding code before, around or inside a template

When overriding a PHTML template, this is needed to add something in the top of the template, in the bottom or right in the middle. In all cases, the best option is to look for a child position in that template, similar to $block->getChildHtml(). However, when this is missing, overriding a template is the only alternative.

But what if you only want to append or prepend more HTML to the template? Overriding a template is a bit expensive for this. Ideally, what you would like to have is an automatic position in the template, either before or after loading the original contents.

Unfortunately, adding another <block> via the XML layout with the same Block class but a different PHTML template is not the same. Data in the block object might be duplicated, loaded twice, bugs might appear.

Additional templates besides the original PHTML template

This is what the Yireo_AdditionalBlockTemplate tries to solve. And it does so with a various simple mechanism. For any template block, the extension allows you to load an additional template (or multiple) on top of the original template, while still using the vary same block instance that was there.

The following XML layout statement shows the logic:

<referenceBlock name="original.block">
    <arguments>
        <argument name="additional_templates" xsi:type="array">
            <item name="example" xsi:type="array">
                <item name="template" xsi:type="string">Yireo_Example::example.phtml</item>
                <item name="position" xsi:type="string">before</item>
            </item>
        </argument>
    </arguments>
</referenceBlock>

Handy right?

See github.com/yireo/Yireo_AdditionalBlockTemplate

Posted on October 8, 2023

About the author

Author Jisse Reitsma

Jisse Reitsma is the founder of Yireo, extension developer, developer trainer and 3x Magento Master. His passion is for technology and open source. And he loves talking as well.

Sponsor Yireo

Looking for a training in-house?

Let's get to it!

We schrijven niet te commerciële dingen, we richten ons op de technologie (waar we dol op zijn) en we komen regelmatig met innovatieve oplossingen. Via onze nieuwsbrief kun je op de hoogte blijven van al deze coolness. Inschrijven kost maar een paar seconden.

Do not miss out on what we say

This will be the most interesting spam you have ever read

We schrijven niet te commerciële dingen, we richten ons op de technologie (waar we dol op zijn) en we komen regelmatig met innovatieve oplossingen. Via onze nieuwsbrief kun je op de hoogte blijven van al deze coolness. Inschrijven kost maar een paar seconden.