Score:2

Can I know what I'm looking at from the URL?

mw flag

I think on Drupal 7 I had previously used something like menu_get_object() to find out what content I was on. For example, with mysite.com/content/my-page, it would tell me that this was a node, its content type, its ID, etc.

Ideally I'm trying to do it even if the URL is the site's front page, I'd like to be able to reverse engineer what content it is showing me.

cn flag
What's your end goal? Knowing that might get you suggestions for different (perhaps better) approaches
Andrew Morris avatar
mw flag
@Clive, I already have a system that is sending analytics data based on the URL the user is on, but it can get confused if the default homepage is set to something else within the site, because they could have visited the homepage anonymous or authenticated. Unfortunately I'm not building it for a once use case, it's for multiple sites, so that's why I want something kinda open-ended for any of my platforms I send it to
Andrew Morris avatar
mw flag
Which is why I wanted to see if there was an easy enough way to get Drupal to tell me what page you are on, so that I could also send that data, as well as just my URL
cn flag
Ah I see, that makes sense. I think that's quite difficult to do generically, as the answer below mentions you can do it per-entity type easily enough but I think you'll need to test for all of the different things the page could be manually, rather than Drupal telling you
Score:2
cn flag

You are looking for a route parameter, which is automatically upcasted to an entity object if you are on an entity route.

For example on a node route:

use Drupal\node\NodeInterface;

  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof NodeInterface) {
    $content_type = $node->getType();
    $id = $node->id();
  }
Andrew Morris avatar
mw flag
Ah excellent, thank you
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.