Is there a way to set optional route location parts? - laravel

firstly, I am not sure how to structure the question title correctly, feel free to edit it to represent the question correctly. I will try to explain what I mean.
I implemented localization on my app (URL of tutorial is at bottom of this post), and I have created my route as follows:
// Set language
Route::get('lang/{locale}', 'PagesController#lang');
And it works. But only on pages which have only one "level" in the url:
example.com/first-level - changing language works on these URLs
example.com/first-level/second-level - changing language doesn't work on these pages
At first I thought the problem is with url parameters, cause by chance, the pages where I first noticed changing language didn't work was on a url which has a route with an parameter like this
example.com/first-level/{id}
So then I tried to rewrite the route for changing languages to this (added an optional parameter)
// Set language
Route::get('lang/{optional?}/{locale}', 'PagesController#lang');
But that didn't work either
The language is changed by anchor tags which point to the route
<a href="lang/en">English</
Serbian
Expected result: being able to change the language from whichever page the links are clicked. Clicking the links on pages like example.com/one/two and example.com/one/{id}/two are supposed to work.
Actual results: changing language works only on example.com and pages like example.com/one , and fails on example.com/one/two and example.com/one/{id}/two . When the links are clicked on these pages, the app is sent to an URL like this: example.com/one/lang/en and example.com/one/{id}/lang/en respectively.
I implemented localizations on my project following this tutorial https://appdividend.com/2019/04/01/how-to-create-multilingual-website-using-laravel-localization/#Step_2_Creating_Translation_Files

You can simply define both routes.
Route::get('lang/{locale}', 'PagesController#locale');
Route::get('lang/{optional}/{locale}', 'PagesController#lang');
Then handle the optional variable with your controller methods.
public function locale($locale)
{
return $this->lang(null, $locale);
}
public function lang($optional, $locale)
{
// ... your logic
}
As for your link problem, you need to use an absolute path.
// relative path — https://yourdomain.com/current/path/lang/en
English
Serbian
// absolute path — https://yourdomain.com/lang/en
English
Serbian

Related

ASP.NET Core MVC : Razor pages routing, incorrectly re-using previous route data

I'm working on a dotnet 6 mvc application using RazorPages, and I'm having a problem with strange routing behavior.
I have a RazorPage /Pages/News.cshtml
This page is accessible using the default route /news
When called without any parameters this page will display an index of news articles.
I also want this page to be able to display a specific news article, via a path like this...
/news/1234-my-news-article
To achieve this, I've added a config like so...
builder.Services.AddRazorPages(options =>
{
options.Conventions.AddPageRoute("/News", "News/{id:regex(^\\d+\\-.*)?}");
});
In my templates, I can then use links like this...
<a asp-page="/News" asp-all-route-data="#(new Dictionary<string, string> { { "id", "1234-my-news-article" } })">My News Article</a>
or
<a asp-page="/News">All Articles</a>
However, once I've navigated to a specific article, the index link doesn't render correctly, and will instead link again to the same article. It appears to be re-using the current routing parameters.
Is there some way to avoid this?
update:
I've found a work-around, if I use this tag instead...
<a asp-page="/News" asp-route-id="">All Articles</a>
then it will link correctly to "/news".
It seems a bit counter-intuitive to have to explicitly set this to blank. I would have assumed it would default to unset, unless explicitly set otherwise.
This is known as ambient route values (https://www.learnrazorpages.com/razor-pages/tag-helpers/anchor-tag-helper#ambient-route-values), where the current route values are automatically added to outbound links which are generated by the anchor tag helper if the destination page is the same as the current page. In older versions of Razor Pages, this was the default behaviour for all pages.
As you have discovered, you can override this by setting the route value to an empty string, or as suggested elsewhere, to use a plain anchor tag for your link.
asp-page tag helper will add id value to the route by default.It is by design.If you don't want to add it,you can try to use href to replace asp-page:
All Articles

Laravel lang resetting to ENGLISH with POST route

So here is my problem, I'm able to use Localization with Laravel. I've been using it on GET route, the problem occur with my POST route. For example, I'm in french on my registration page, when I click on register, once I enter my controller, the language is reset to english, but it must not be reset, because my controller is supposed to return a view with a text, so this view is supposed to be in the right language. I tought I could pass the lang through URL parameter, but since it is a POST I cannot and I must not use GET because it's a registration form. The thing is in my route I set the lang to what the lang is already, since it is already in french, from when I accessed the registration page, it should something like lang = 'fr', but no the program act like each time it set the lang to french, to second after it reset it to english. I've been stuck on this for a while and I cannot see the solution, can someone help me ?
Here is my 'french' registration form:
Here is the route 'register' (When you click on register/inscription):
Here is a part of my controller:
Here is the view my controller returns (It is supposed to be written 'fr' not 'en'):
Thanks in advance for your help and your time !
I've found the solution, now when I enter a page like to registration page I do this
And in the function that is triggered when clicking register/inscription I added this at the beginning

In a WordPress plugin admin ajax call, which is the way of using the site's locale?

After upgrading to WordPress 4.7, I changed the language field from my profile to english, while the site's language is set to greek.
I have written a plugin that displays a widget. This widget is refreshing its content via an ajax call. As it is mentioned here (see Note about admin-ajax.php), strings are normally returned in my profile's language (english), but I would prefer to have them in the site's locale (greek).
After adding the statement switch_to_locale( get_locale() ) at the first line of the ajax call action handler, expressions using the default text domain like __( 'Sunday' ) are indeed translated to greek. However, expressions like __( 'Sunday', 'my-plugin-textdomain' ) are never translated.
My question is how can I display strings from the plugin text domain in my site's (and not my profile's) locale during an ajax call?
Note that:
Before switching my profile's locale to english, everything worked fine (that is, all strings were translated to greek).
I am loading the plugin's textdomain in a function triggered by the action plugins_loaded.
Searching the internet didn't lead to helpful results as the feature of setting the user's locale is released recently in the latest version.
It's a late answer but I found out how to load the related text domain before the AJAX call works today, needed to share here:
Add a hidden input field to your form or append to your data this:
<input type='hidden' name='lang' value='<?php echo get_locale();?>'>
or
{
lang: '<?php echo get_locale()?>',
}
Then, just before your load_*_textdomain() function call, write this:
if (isset($_GET["lang"])) {
$locale = $_GET["lang"];
add_filter('determine_locale', function()use($locale){ return $locale; });
}
It'll switch the locale to the desired locale. Note, the locales are like en_US or el relative to your .mo filenames.

Use anchor tag to link to same page using react router hashlocation

Trying to link to the same page with anchor tag but as i am using react router HashLocation as below, router catches it preventing the anchor to work as normal in addition of producing error of "No route matches path".
Router.run(routes, Router.HashLocation, (Root) => { React.render(<Root/>, document.body); });
Same Problem has been asked in the link below with some hint of using "HistoryLocation" but i want to stick with "HashLocation" and those link do not provide concrete answer, thus need help:
1) How to use normal anchor links with react-router
2) Using React-Router to link within a page
I wonder if there are some kind of filter in router to exclude some hash so that i can use default same page anchor linking.
The whole point of using the HashLocation router is to use the # to handle routing, it's a bit of a hack to allow client side navigation, but in fact it's a Single Page Application.
You can't have more than one # in your url, it makes no sense for browsers to have multiple ones. With that in mind, I think you should handle the "in page" navigation (but in fact your whole site is the "in page navigation") yourself, maybe simply using some jQuery (or pure javascript) code to scroll to the specified DOM id maybe on some hook after react-router transition.
Try something like this.
componentDidUpdate() { if ((this.props.index == this.props.selected)) React.findDOMNode(this).scrollIntoView(); }

CodeIgniter Url Rewrite (language dependent)

So, i have my .htaccess, my controllers, everything is going fine. I added localization, so now i have Portuguese(Default), English and Italian.
I am using the _lang files in the appplication/languages directory, i am using session->userdata('lang') and everything works fine.
My controllers are named with portuguese words, after the top menu. What i'm looking for is:
to rewrite my url, changing the name of the controller, depending on the session->userdata('lang').
Is this even possible? how?
Thank you
So i am trying, as InFog suggested, in the routes file:
if ($this->session->userdata('lang') == 'english') {
$route['novidades/([a-z]+)'] = 'news/$1';
}
but i just get a blank screen when i open the application.
And i've tried it without the if clause, and nothing happens, when i go to
http://localhost/myapp/novidades
the url stays the same
You can solve this using CodeIgniter Routes. You can do it editing the file 'system/application/config/routes.php:
$route['news/([a-z]+)'] = 'noticias/$1';
This way an URL like '/news/run-fools' will be remaped to 'noticias/run-fools'. Now you can have just one controller =)
Good Luck
Override CI_Router to translate the name in the fetch_class() method to change controllers. Override fetch_method() to change methods.

Resources