The problem

My Magento 2 (v2.4.5-p5) admin is unable to display the entries in the “Layout” dropdown with their correct translations, despite the correct translations being present.

The layouts are defined in vendor/magento/module-theme/view/frontend/layouts.xml and additionally in vendor/magento/module-page-builder/view/frontend/layouts.xml, when you are using the PageBuilder module.




    
        
    
    
        
    
    
        
    
    
        
    



    
        
    
    
        
    
    
        
    

After tracking down the values from KnockoutJS downwards using xdebug, I came across the culprit: The PageLayout Config.php file of the Magento framework. So as deep down in the core as it basically gets.

The method in question is called _extractData(). This method is supplied with the layout files XML DOM and returns the values (the names) of all the specified layouts. However, there is one problem with this logic: It completely ignores the translate="true" flag for each label tag.

/**
    * Extract configuration data from the DOM structure
    *
    * @param \DOMDocument $dom
    * @return array
    */
protected function _extractData(\DOMDocument $dom)
{
    $result = [];

    /** @var \DOMElement $layout */
    foreach ($dom->getElementsByTagName('layout') as $layout) {
        $result[$layout->getAttribute('id')] = $layout->nodeValue !== null ? trim($layout->nodeValue) : '';
    }
    return $result;
}

The solution

To fix this behaviour, you simply have to override the _extractData() method with a corrected version, which respects the translation.

Set up your own custom module with the following structure:

app/
└── code/
    └── /
        └── /
            ├── registration.php
            ├── etc/
            │   ├── module.xml
            │   └── di.xml
            └── Overrides/
                └── PageLayoutConfig.php
_",
    __DIR__
);



    _" setup_version="1.0.0">
    



    \\Overrides\PageLayoutConfig" />
\\Overrides;

class PageLayoutConfig extends \Magento\Framework\View\PageLayout\Config {
    protected function _extractData(\DOMDocument $dom) {
        $result = [];
        foreach ($dom->getElementsByTagName('layout') as $layout) {
            $label = trim($layout->nodeValue);
            if ('true' === (string)simplexml_import_dom($layout)->{'label'}['translate']) {
                $label = __($label);
            }
            $result[$layout->getAttribute('id')] = $label;
        }
        return $result;
    }
}

After you deployed your module to your Magento installation, make sure to activate it.

php bin/magento module:enable _
php bin/magento setup:upgrade

Refresh your page and there you have it: The translations are working now.

You’re welcome.

Leave a Reply

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

You May Also Like