Using Global Translations in Panel

Hey guys,

Would anyone be able to tell me how/if I can use global translations in the panel? In the code, you can use t(‘translation-key’). Would it be possible to use this function or another method to get the global translation in the panel?

Any and all tips are very much appreciated :slight_smile:

Thanks,
Dan

Do you mean in blueprints or in custom Panel fields/views/blocks etc.?

Yes, in the panel content, textareas, blocks, etc.

In textareas, you could use placeholders like `{{ my.super.key }} which you could then replace in kirbytext hooks. In blocks or other fields, you could also work with a preg_replace callback.

Sorry, still a bit unfamiliar with both of these functionalities, for the hooks would something like this work:

'hooks' => [
        'kirbytext:after' => function ($text) {
            $key = {{ translation-key }};

            return t($key);
        }
    ]

or with preg_replace:

echo preg_replace($page->content()->value(), 'translation key in text', t('translation key in code');

Would it be simpler to use preg_replace for all scenarios?

Yes, I think so, because different methods for different use cases don’t really make that much sense. Basically, you would search for strings within given delimiters (it’s up to you, whether you use double curly braces or something else that is not otherwise used), and then call the t() method on those matches.

Great, so if I was to do:

echo preg_replace($page->content()->value(), 'translation key in text', t('translation key in code');

Would this be the correct syntax?
Also, is there a way to do this globally across the whole project so I wouldn’t have to wrap every content field with preg_replace?

Your syntax/order of arguments is not correct and you would of course need a regex pattern, see the docs: PHP: preg_replace - Manual

I don’t think you can do this globally, but you could create a custom field method that you can string on any relevant field.

Ah okay, so I could use a special character in the content to match with the pattern in the function?

For example, I could specify that anything with ## in front would be placed in the regex pattern, so in the content, it would be ##translate-hello.

Then the function could look like this:

echo preg_replace(/##/i, $page->content()->value(), t('translation key in code');

Although do you know if this could be made dynamic somehow? So that it would get the key after the translation symbol (##).