Hey there,
I've been trying to add multiple languages to my website, but it seems that I'm doing something wrong. I saw multiple topics with this issue and no solution at all. People were complaining in CodeIgniter's Github issues section and their threads were closed, without an answer.
I'd like to have a default language 'en'
public $defaultLocale = 'en';
public $negotiateLocale = false;
public $supportedLocales = ['fr'];
And I want to have these kinds of URLs:
website.com/fr/blog
website.com/fr/services
website.com/fr/contacts
website.com/fr
website.com/blog
website.com/services
website.com/contacts
website.com
Notice that there is no website.com
/en/something. The reason is that this is a requirement for SEO to be good enough for Google.
In order to make proper routes for this, my Routes.php should look like that:
$routes->get('{locale}/blog', 'Blog::index');
$routes->get('{locale}/services', 'Services::index');
$routes->get('{locale}/contacts', 'Contacts::index');
$routes->get('{locale}', 'Home::index');
$routes->get('blog', 'Blog::index');
$routes->get('services', 'Services::index');
$routes->get('contacts', 'Contacts::index');
$routes->get('', 'Home::index');
I.e. I'll have to duplicate all my routes in order to have both languages supported. I got 100+ routes and this is really not an option for me.
How can I have this route:
'{locale}/blog'and have it opened with and without provided locale in the url?
I'm experimenting with one super-ugly solution right now, that on the first glance seems to work. But I really don't like it, because it's a workaround and far from the proper way of doing things.
PHP Code:
$routesOptions = $routes->getRoutesOptions(null, 'get');
foreach ($routes->getRoutes('get') as $key => $row) {
$options = $routesOptions[$key] ?? [];
if (isset($options['redirect'])) {
$redirectTo = is_array($row) ? key($row) : $row;
$routes->addRedirect("{locale}/{$key}", "{locale}/{$redirectTo}");
} else {
if (is_string($row)) {
$routes->get("{locale}/{$key}", $row, $options);
} else {
$routes->get("{locale}/{$key}", function () {}, $options);
}
}
}