October CMS resources and help articles

Simple and to the point. Optimized by the community.

Make plugin translation keys available as theme messages for RainLab.Translate

6
by octobertricks@luketowers.ca, last modified on December 5th, 2019

This trick is a handy way of distributing RainLab.Translate-ready translations with your plugin so that they can be used and overridden by themes.

<?php namespace Acme\Demo;

use Lang;
use Event;
use System\Classes\PluginBase;

class Demo extends PluginBase
{
    public function boot()
    {
        Event::listen('cms.theme.extendConfig', function ($dirName, &$config) {
            $locales = [];
            $results = [];
            $prefix = 'frontend';
            $loader = Lang::getLoader();

            // Get the namespace of the current plugin
            $namespace = str_replace('\\', '.', strtolower(__NAMESPACE__));

            // Scan for available languages under this plugin
            $localeDirectories = glob(plugins_path(str_replace('.', '/', $namespace) . '/lang/*', GLOB_ONLYDIR));
            if (empty($localeDirectories)) {
                return;
            }
            foreach ($localeDirectories as $dir) {
                $locales[] = pathinfo($dir, PATHINFO_BASENAME);
            }

            // Load the messages under the given prefix and prepare them for use
            // as frontend messages
            foreach ($locales as $locale) {
                $translations = $loader->load($locale, 'lang', $namespace);

                if (!empty($translations[$prefix])) {
                    $results[$locale] = array_dot($translations[$prefix]);
                }
            }

            if (empty($results)) {
                return;
            }

            // Load the plugin's messages into the theme's config, deferring to theme defined messages if present
            foreach ($results as $locale => $messages) {
                $config['translate'][$locale] = array_merge($messages, @$config['translate'][$locale] ?: []);
            }
        });
    }
}

Discussion

0 comments

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