0

I'm trying to get the Content Type value of a node page (that the user is currently visiting - let's call it CT-1)... and feed that value as a variable into a DIFFERENT content type's node.html.twig template (CT-2). This CT-2 template is being used in a View output, displaying on a CT-1 page. Here's my code...

function custom_mods_preprocess_node(array &$variables, $hook) {
   if ($node = \Drupal::request()->attributes->get('node')) {
     $variables['pageNodeType'] = $node->getType();
   }
 }

Then I print out the pageNodeType variable into CT-2's node.html.twig template like so...

{% if pageNodeType == 'TYPE' %}
<div>TEST</div>
{% endif %}

This all works perfectly on page load. But when the view output is filtered with AJAX (via an exposed filter), pageNodeType becomes NULL, and therefore the "if statement" breaks with the CT-2 template.

What can I do to keep that variable active after an ajax update?

I tried leveraging..

\Drupal::request()->headers->get('referer');

..to pull the previous page, but it seemed like quite a task to get the Content Type via this approach. Is there a better way.

Thanks!!

Edit: May be related to this post as well... but no answers? Views with ajax get current node in hook_views_query_alter

2
  • Just out of curiosity: Why don't you use node--[content-type].html.twig? As suggested here: drupal.org/docs/8/theming/twig/…
    – nhck
    Commented Apr 24, 2020 at 10:00
  • The node.html.twig is for a single content type that's being displayed on ANOTHER content types page, and needs different values based on whichever content type that page is.
    – Yuckle
    Commented Apr 24, 2020 at 20:35

1 Answer 1

0

Well, here's what I came up with... and it's working as needed. If there are issues with this approach, please feel free to critique. My backend skills leave much to be desired. Thanks!

function custom_mods_preprocess_node(array &$variables, $hook) {

// Get the current page's content type on page load
$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  $variables['pageNodeType'] = $node->getType();
}

// Keeps the type available if an AJAX call happens 
if (\Drupal::routeMatch()->getRouteName() == 'views.ajax') {
  $previousUrl = \Drupal::request()->headers->get('referer');
  $fake_request = Request::create($previousUrl);
  $url_object = \Drupal::service('path.validator')->getUrlIfValid($fake_request->getRequestUri());
  if ($url_object) {
    $route_params = $url_object->getRouteParameters();
    $ent_id = $route_params['entity_id'];
    $node = \Drupal\node\Entity\Node::load($ent_id);
    $variables['pageNodeType'] = $node->getType();
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.