Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- use Drupal\views\Views;
- // Optional, if using filter values passed via URL (see example below).
- use Drupal\Component\Utility\Html;
- /**
- * Preprocesses variables for node--NODE_TYPE.html.twig.
- *
- * Replace 'mytheme' with the name of your theme, and NODE_TYPE and VIEW_NAME
- * with actual machine names.
- */
- function mytheme_preprocess_node__NODE_TYPE(&$variables) {
- $node = $variables['node'];
- // Execute the view that provides the context.
- $view = \Drupal\views\Views::getView('VIEW_NAME');
- // Optionally set a contextual filter value passed in via the URL;
- // e.g. path-to-node?vid=456. You will need to add the parameter to the pager
- // URLs in your Twig template.
- $variables['arg'] = Html::escape(\Drupal::request()->query->get('vid'));
- $view->setArguments([$variables['arg']]);
- $view->execute();
- // Iterate through the results to find the results index for previous,
- // current, and next nodes.
- $match = FALSE;
- foreach ($view->result as $k => $row) {
- // Break out of iterator when we find the next row.
- if ($match !== FALSE) {
- $next = $k;
- break;
- }
- // This result matches our currently loaded node.
- if ($row->nid == $node->id()) {
- $match = $k;
- }
- // As long as we haven't reached a match, let's keep updating $previous.
- if ($match === FALSE) {
- $previous = $k;
- }
- }
- // If a match is found, set up our template variables.
- if ($match !== FALSE) {
- $variables['node_view_pager'] = [];
- $variables['node_view_pager']['num_results'] = count($view->result);
- $variables['node_view_pager']['index'] = $match + 1;
- $controller = \Drupal::entityManager()->getStorage('node');
- if (isset($previous)) {
- $variables['node_view_pager']['previous'] = $controller->load($view->result[$previous]->nid);
- }
- if (isset($next)) {
- $variables['node_view_pager']['next'] = $controller->load($view->result[$next]->nid);
- }
- }
- }
Add Comment
Please, Sign In to add comment