Score:-2

How to get previous clicked on link and previous page url in Drupal from a TWIG

cn flag

Ive tried several ways of getting the previous page url and what link they clicked on within a twig file. How do you accomplish this from a twig in Drupal9.

I have tried the following JS in twig but its not rendering.

<script type="text/javascript">
    document.write(document.referrer);
</script>

I had solved it by using JQuery. It's for building a mailto: string that auto populated an email with what link a user clicked on and what page they came from on a page 404. When they hit contact us it prepares a nice email.

First, in Drupal setup the correct page suggestion for error handling:

$route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    case 'system.401':
      // Unauthorized Access.
      $error = 401;
      break;

    case 'system.403':
      // Access Denied.
      $error = 403;
      break;

    case 'system.404':
      // Page Not Found.
      $error = 401;
      break;

    case 'system.500':
      // Something went wrong.
      $error = 401;
      break;

    case 'system.503':
      // Service unavailable.
      $error = 503;
      break;

    case 'system.504':
      // Gateway timeout.
      $error = 504;
      break;
  
    
  }
  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }

}

The JQuery:

$('body a').on('click', function(){
      localStorage.setItem('clickedURL', $(this).attr("href"));
  });

Unless someone has a better way please share.

id flag
Putting inline scripts in Twig templates is not Drupal's JavaScript API.
unixmiah avatar
cn flag
I had a different approach with javascript which worked for me
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.