0

I'm having some trouble in order to get a view's name and the display ID in a template_preprocess_node function.
I have a custom content type and a view with two different displays.
My idea is to define a variable in the preprocess function related to the content type (using theme_preprocess__content_type_name function), in order to use this variable in the Twig template to switch between the displays, according to the number of results.

I understand that in order to use a variable in the preprocess function, it has to be defined somehow in the template (correct me if I got this wrong).
So my question is: how can I call the view and the display in the node preprocess function?

EDIT 1: Using Hudri suggestion:

function theme_name_preprocess_node__content_type(&$variables) {

    $route = \Drupal::routeMatch()->getRouteObject();
    $view_id = $route->getDefault('view_id');
    $display_id = $route->getDefault('display_id');
    if($view_id == 'view_name' && $display_id == 'display_name'){
        $counter = count($view_id->result);
        $variables['count'] = $counter;
    }
}

Can the variable count be used in the Twig template in an if clause?

1 Answer 1

4

I'm assuming you're using a view page to display your content type:

$route = \Drupal::routeMatch()->getRouteObject();
$view_id = $route->getDefault('view_id');
$display_id = $route->getDefault('display_id');
1
  • Thank you for your answer. Actually I'm not using a view page, but a block called in the Twig template. I updated the question, to be more specific. Commented Jan 24, 2019 at 11:45

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.