Translate exception messages in frontend
When you have use cases like creating pages or users from the frontend programmatically, you might run into the issue that exceptions messages are always output in English in a single language site, even though Kirby provides translations for these messages.
A typical simple example could look like this:
We try to create a new blog article and echo the error message in case the action fails, for example, because a page with the given slug already exists: "A page draft with the URL appendix "my-awesome-post" already exists"
One way to solve this problem is to call the I18::template()
method with the desired language code:
This is totalle fine for a single message. Alternatively, you can set the I18n::$locale
property depending on context in your controller, template etc.:
This will now output the exception message in the given language if it exists, or fall back to English if it doesn't.
To make these code snippets more versatile, you can replace the hard-coded language string with the locale option set in your config.php
:
Then use this option in your code: