Score:0

How to get path/URL without language prefix (for multilingual site)

sh flag

I have written a code to get the parameters (node_id, taxonomy_id) from the URL using the following code.

Sample URL: /foo/bar/[nid]\/[tid]

$path = \Drupal::request()->getpathInfo();
$arg = explode('/', $path);
$node_id = $arg[3]; //gives [nid]
$term_id = $arg[4]; // gives [tid]

This works, but when I switch to other language (say spanish), the URL becomes

/es/foo/bar/[nid]/[tid]

So obviously the code doesn't work in this case. Is there anyway to handle this?

leymannx avatar
ne flag
Can you please inspect what `Drupal::routeMatch()->getParameters()` is returning you?
Krishna Mohan avatar
sh flag
I think I see what you're saying, I think we can get node/taxonomy object using this.. but what about the parameter 'foo' and 'bar' how should I check them?
leymannx avatar
ne flag
What's with `\Drupal::routeMatch()->getRouteName();`?
Krishna Mohan avatar
sh flag
thank you @leymannx, I did learn something from you today.. and I have got the solution. :)
Score:0
sh flag

I got it. Here's the code to get the URL without language prefix.

use Drupal\Core\Url;
$current_url = Url::fromRoute('<current>');
// If we want to get the url without language prefix
$path = $current_url->getInternalPath();
$path_args = explode('/', $path);
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.