October CMS resources and help articles

Simple and to the point. Optimized by the community.

Override Translations with a Plugin

20
by danharrin, last modified on November 28th, 2019

October allows users to override translations on a per-site basis very easily, through the use of a /lang directory in the project's root. But what happens when these changes need to be bundled with a plugin, so they don't need to be applied manually per installation?

Luckily, there is a very useful translator.beforeResolve event that allows translation results to be modified before they are returned back to the application.

With some slight enhancements, you are able to override any translation string present in your October app with a single event listener in your plugin's boot() method:

use Event;
use Lang;

public function boot()
{
        Event::listen('translator.beforeResolve', function ($key, $replace, $locale) {
                $plugin = 'author.plugin'; // Replace this string with the path of the plugin this is being executed from

                // Check the translation doesn't originate from this plugin
                if (substr($key, 0, strlen($plugin)) != $plugin) {
                        // Contruct a possible translation path
                        $path = $plugin . '::lang.' . str_replace('::', '.', $key);

                        // Retrieve its results
                        $result = Lang::get($path);

                        // If an overriding translation is found, return it
                        if ($result != $path) {
                                return $result;
                        }
                }
        });
}

Now, you can modify any translation in your plugin's lang.php files, like so:

<?php return [
    'acme' => [
        'blog' => [
            'lang' => [
                'plugin' => [
                    'name' => 'My Blog', // acme.blog::lang.plugin.name is overriden with 'My Blog'
                ],
            ],
        ],
    ],
    'backend' => [
        'lang' => [
            'user' => [
                'menu_label' => 'Users', // backend::lang.user.menu_label is overriden with 'Users'
            ],
        ],
    ],
];

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?