Localized urls for multilanguage website (same as mcamara / laravel-localization) #3468
-
Is there a way or a package that we can use for localized urls in AdonisJS v4.1 just like in Laravel? Example of prefixing language: Route.get('/', 'IndexController.index') -> Dutch
Route.get('/en', 'IndexController.index') -> English
Route.get('/fr', 'IndexController.index') -> French this Route.group(() => {
Route.get('/', 'IndexController.index')
}).prefix(LANG-PREFIX) Laravel Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'IndexController@index');
}); Example of translated url: Route.get('/artikelen', 'IndexController.index') -> Dutch
Route.get('/en/articles', 'IndexController.index') -> English
Route.get('/fr/des-articles', 'IndexController.index') -> French |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I haven't tested it but normally something like this should work: Route.group(() => {
Route.get('/', 'IndexController.index')
}).prefix(':lang').middleware('validateLangPrefix') Then you could make a middleware that validates that the prefix export default class ValidateLangPrefix {
public async handle({ request }: HttpContextContract, next: () => Promise<void>) {
const lang = request.param('lang')
if (!['fr', 'en', 'it'].includes(lang.toLowerCase())) {
// Throw error or return 404 for you users
throw new Error(`Invalid locale: ${lang}`)
}
await next()
}
} Read this for more information on how to make middleware: Another solution would be to dynamically create your routes according to your locales, I don't think it's very complicated, but it requires some custom code. |
Beta Was this translation helpful? Give feedback.
I haven't tested it but normally something like this should work:
Then you could make a middleware that validates that the prefix
:lang
is validRead this for more information on how to make middleware:
https://docs.adonisjs.c…