views.theme.inc 39.1 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2 3 4 5 6 7
<?php

/**
 * @file
 * Preprocessors and helper functions to make theming easier.
 */

8
use Drupal\Component\Utility\Html;
9
use Drupal\Component\Utility\Xss;
10
use Drupal\Core\Template\Attribute;
11
use Drupal\Core\Url;
12

merlinofchaos's avatar
merlinofchaos committed
13
/**
14 15 16 17
 * Prepares variables for view templates.
 *
 * Default template: views-view.html.twig.
 *
18
 * @param array $variables
19 20
 *   An associative array containing:
 *   - view: The ViewExecutable object.
merlinofchaos's avatar
merlinofchaos committed
21
 */
22 23
function template_preprocess_views_view(&$variables) {
  $view = $variables['view'];
24
  $id = $view->storage->id();
merlinofchaos's avatar
merlinofchaos committed
25

26 27
  $variables['css_name'] = Html::cleanCssIdentifier($id);
  $variables['id'] = $id;
28
  $variables['display_id'] = $view->current_display;
29 30 31 32 33
  // Override the title to be empty by default. For example, if viewing a page
  // view, 'title' will already be populated in $variables. This can still be
  // overridden to use a title when needed. See views_ui_preprocess_views_view()
  // for an example of this.
  $variables['title'] = '';
merlinofchaos's avatar
merlinofchaos committed
34

35
  $css_class = $view->display_handler->getOption('css_class');
merlinofchaos's avatar
merlinofchaos committed
36
  if (!empty($css_class)) {
37 38
    $variables['css_class'] = preg_replace('/[^a-zA-Z0-9- ]/', '-', $css_class);
    $variables['attributes']['class'][] = $variables['css_class'];
merlinofchaos's avatar
merlinofchaos committed
39 40
  }

41 42 43 44 45 46 47 48 49 50 51 52
  // contextual_preprocess() only works on render elements, and since this theme
  // hook is not for a render element, contextual_preprocess() falls back to the
  // first argument and checks if that is a render element. The first element is
  // view_array. However, view_array does not get set anywhere, but since we do
  // have access to the View object, we can also access the View object's
  // element, which is a render element that does have #contextual_links set if
  // the display supports it. Doing this allows contextual_preprocess() to
  // access this theme hook's render element, and therefore allows this template
  // to have contextual links.
  // @see views_theme()
  $variables['view_array'] = $variables['view']->element;

merlinofchaos's avatar
merlinofchaos committed
53 54 55
  // Attachments are always updated with the outer view, never by themselves,
  // so they do not have dom ids.
  if (empty($view->is_attachment)) {
56 57
    // Our JavaScript needs to have some means to find the HTML belonging to
    // this view.
merlinofchaos's avatar
merlinofchaos committed
58 59 60 61
    //
    // It is true that the DIV wrapper has classes denoting the name of the view
    // and its display ID, but this is not enough to unequivocally match a view
    // with its HTML, because one view may appear several times on the page. So
62 63
    // we set up a hash with the current time, $dom_id, to issue a "unique"
    // identifier for each view. This identifier is written to both
64
    // drupalSettings and the DIV wrapper.
65
    $variables['dom_id'] = $view->dom_id;
merlinofchaos's avatar
merlinofchaos committed
66 67 68 69
  }
}

/**
70 71 72 73
 * Prepares variables for views fields templates.
 *
 * Default template: views-view-fields.html.twig.
 *
74
 * @param array $variables
75 76 77 78 79 80 81 82 83 84 85 86
 *   An associative array containing:
 *   - view: The view object.
 *   - options: An array of options. Each option contains:
 *     - inline: An array that contains the fields that are to be
 *       displayed inline.
 *     - default_field_elements: If default field wrapper
 *       elements are to be provided.
 *     - hide_empty: Whether the field is to be hidden if empty.
 *     - element_default_classes: If the default classes are to be added.
 *     - separator: A string to be placed between inline fields to keep them
 *       visually distinct.
 *    - row: An array containing information about the current row.
merlinofchaos's avatar
merlinofchaos committed
87
 */
88 89
function template_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
90 91 92

  // Loop through the fields for this view.
  $previous_inline = FALSE;
93
  $variables['fields'] = []; // ensure it's at least an empty array.
94 95
  /** @var \Drupal\views\ResultRow $row */
  $row = $variables['row'];
merlinofchaos's avatar
merlinofchaos committed
96 97
  foreach ($view->field as $id => $field) {
    // render this even if set to exclude so it can be used elsewhere.
98
    $field_output = $view->style_plugin->getField($row->index, $id);
99
    $empty = $field->isValueEmpty($field_output, $field->options['empty_zero']);
100
    if (empty($field->options['exclude']) && (!$empty || (empty($field->options['hide_empty']) && empty($variables['options']['hide_empty'])))) {
merlinofchaos's avatar
merlinofchaos committed
101
      $object = new stdClass();
102
      $object->handler = $view->field[$id];
103
      $object->inline = !empty($variables['options']['inline'][$id]);
104 105 106
      // Set up default value of the flag that indicates whether to display a
      // colon after the label.
      $object->has_label_colon = FALSE;
merlinofchaos's avatar
merlinofchaos committed
107

108
      $object->element_type = $object->handler->elementType(TRUE, !$variables['options']['default_field_elements'], $object->inline);
merlinofchaos's avatar
merlinofchaos committed
109
      if ($object->element_type) {
110
        $attributes = [];
merlinofchaos's avatar
merlinofchaos committed
111
        if ($object->handler->options['element_default_classes']) {
112
          $attributes['class'][] = 'field-content';
merlinofchaos's avatar
merlinofchaos committed
113 114
        }

115
        if ($classes = $object->handler->elementClasses($row->index)) {
116
          $attributes['class'][] = $classes;
merlinofchaos's avatar
merlinofchaos committed
117
        }
118
        $object->element_attributes = new Attribute($attributes);
merlinofchaos's avatar
merlinofchaos committed
119 120 121
      }

      $object->content = $field_output;
122 123
      if (isset($view->field[$id]->field_alias) && isset($row->{$view->field[$id]->field_alias})) {
        $object->raw = $row->{$view->field[$id]->field_alias};
merlinofchaos's avatar
merlinofchaos committed
124 125 126 127 128
      }
      else {
        $object->raw = NULL; // make sure it exists to reduce NOTICE
      }

129
      if (!empty($variables['options']['separator']) && $previous_inline && $object->inline && $object->content) {
130
        $object->separator = Xss::filterAdmin($variables['options']['separator']);
merlinofchaos's avatar
merlinofchaos committed
131 132
      }

133
      $object->class = Html::cleanCssIdentifier($id);
merlinofchaos's avatar
merlinofchaos committed
134 135

      $previous_inline = $object->inline;
136 137 138 139
      // Set up field wrapper element.
      $object->wrapper_element = $object->handler->elementWrapperType(TRUE, TRUE);
      if ($object->wrapper_element === '' && $variables['options']['default_field_elements']) {
        $object->wrapper_element = $object->inline ? 'span' : 'div';
merlinofchaos's avatar
merlinofchaos committed
140 141
      }

142 143
      // Set up field wrapper attributes if field wrapper was set.
      if ($object->wrapper_element) {
144
        $attributes = [];
merlinofchaos's avatar
merlinofchaos committed
145
        if ($object->handler->options['element_default_classes']) {
146 147
          $attributes['class'][] = 'views-field';
          $attributes['class'][] = 'views-field-' . $object->class;
merlinofchaos's avatar
merlinofchaos committed
148 149
        }

150
        if ($classes = $object->handler->elementWrapperClasses($row->index)) {
151
          $attributes['class'][] = $classes;
merlinofchaos's avatar
merlinofchaos committed
152
        }
153
        $object->wrapper_attributes = new Attribute($attributes);
merlinofchaos's avatar
merlinofchaos committed
154 155
      }

156 157 158 159
      // Set up field label
      $object->label = $view->field[$id]->label();

      // Set up field label wrapper and its attributes.
merlinofchaos's avatar
merlinofchaos committed
160
      if ($object->label) {
161
        // Add a colon in a label suffix.
merlinofchaos's avatar
merlinofchaos committed
162
        if ($object->handler->options['element_label_colon']) {
163
          $object->label_suffix = ': ';
164
          $object->has_label_colon = TRUE;
merlinofchaos's avatar
merlinofchaos committed
165 166
        }

167 168 169 170 171
        // Set up label HTML element.
        $object->label_element = $object->handler->elementLabelType(TRUE, !$variables['options']['default_field_elements']);

        // Set up label attributes.
        if ($object->label_element) {
172
          $attributes = [];
merlinofchaos's avatar
merlinofchaos committed
173
          if ($object->handler->options['element_default_classes']) {
174 175
            $attributes['class'][] = 'views-label';
            $attributes['class'][] = 'views-label-' . $object->class;
merlinofchaos's avatar
merlinofchaos committed
176 177
          }

178
          // Set up field label.
179
          $element_label_class = $object->handler->elementLabelClasses($row->index);
merlinofchaos's avatar
merlinofchaos committed
180
          if ($element_label_class) {
181
            $attributes['class'][] = $element_label_class;
merlinofchaos's avatar
merlinofchaos committed
182
          }
183
          $object->label_attributes = new Attribute($attributes);
merlinofchaos's avatar
merlinofchaos committed
184 185 186
        }
      }

187
      $variables['fields'][$id] = $object;
merlinofchaos's avatar
merlinofchaos committed
188 189 190 191 192 193
    }
  }

}

/**
194 195 196 197
 * Prepares variables for views single grouping templates.
 *
 * Default template: views-view-grouping.html.twig.
 *
198
 * @param array $variables
199 200 201 202 203 204 205
 *   An associative array containing:
 *   - view: The view object.
 *   - rows: The rows returned from the view.
 *   - grouping_level: Integer indicating the hierarchical level of the
 *     grouping.
 *   - content: The content to be grouped.
 *   - title: The group heading.
206
 */
207 208
function template_preprocess_views_view_grouping(&$variables) {
  $variables['content'] = $variables['view']->style_plugin->renderGroupingSets($variables['rows'], $variables['grouping_level']);
merlinofchaos's avatar
merlinofchaos committed
209 210 211
}

/**
212
 * Prepares variables for views field templates.
merlinofchaos's avatar
merlinofchaos committed
213
 *
214 215
 * Default template: views-view-field.html.twig.
 *
216
 * @param array $variables
217 218 219 220 221
 *   An associative array containing:
 *   - field: The field handler object for the current field.
 *   - row: Object representing the raw result of the SQL query for the current
 *     field.
 *   - view: Instance of the ViewExecutable object for the parent view.
merlinofchaos's avatar
merlinofchaos committed
222
 */
223 224
function template_preprocess_views_view_field(&$variables) {
  $variables['output'] = $variables['field']->advancedRender($variables['row']);
merlinofchaos's avatar
merlinofchaos committed
225 226 227
}

/**
228 229 230 231 232 233
 * Prepares variables for views summary templates.
 *
 * The summary prints a single record from a row, with fields.
 *
 * Default template: views-view-summary.html.twig.
 *
234
 * @param array $variables
235 236 237
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
merlinofchaos's avatar
merlinofchaos committed
238
 */
239
function template_preprocess_views_view_summary(&$variables) {
240
  /** @var \Drupal\views\ViewExecutable $view */
241
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
242 243
  $argument = $view->argument[$view->build_info['summary_level']];

244
  $url_options = [];
merlinofchaos's avatar
merlinofchaos committed
245 246 247 248 249

  if (!empty($view->exposed_raw_input)) {
    $url_options['query'] = $view->exposed_raw_input;
  }

250
  $active_urls = [
251 252
    // Force system path.
    \Drupal::url('<current>', [], ['alias' => TRUE]),
253 254
    // Force system path.
    Url::fromRouteMatch(\Drupal::routeMatch())->setOption('alias', TRUE)->toString(),
255 256
    // Could be an alias.
    \Drupal::url('<current>'),
257 258
    // Could be an alias.
    Url::fromRouteMatch(\Drupal::routeMatch())->toString(),
259
  ];
260
  $active_urls = array_combine($active_urls, $active_urls);
merlinofchaos's avatar
merlinofchaos committed
261

262 263 264
  // Collect all arguments foreach row, to be able to alter them for example
  // by the validator. This is not done per single argument value, because this
  // could cause performance problems.
265
  $row_args = [];
merlinofchaos's avatar
merlinofchaos committed
266

267
  foreach ($variables['rows'] as $id => $row) {
268
    $row_args[$id] = $argument->summaryArgument($row);
merlinofchaos's avatar
merlinofchaos committed
269
  }
270
  $argument->processSummaryArguments($row_args);
merlinofchaos's avatar
merlinofchaos committed
271

272
  foreach ($variables['rows'] as $id => $row) {
273
    $variables['rows'][$id]->attributes = [];
274
    $variables['rows'][$id]->link = $argument->summaryName($row);
merlinofchaos's avatar
merlinofchaos committed
275 276 277 278 279
    $args = $view->args;
    $args[$argument->position] = $row_args[$id];

    if (!empty($argument->options['summary_options']['base_path'])) {
      $base_path = $argument->options['summary_options']['base_path'];
280 281
      $tokens = $view->getDisplay()->getArgumentsTokens();
      $base_path = $argument->globalTokenReplace($base_path, $tokens);
282 283 284
      // @todo Views should expect and store a leading /. See:
      //   https://www.drupal.org/node/2423913
      $url = Url::fromUserInput('/' . $base_path);
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
      try {
        /** @var \Symfony\Component\Routing\Route $route */
        $route_name = $url->getRouteName();
        $route = \Drupal::service('router.route_provider')->getRouteByName($route_name);

        $route_variables = $route->compile()->getVariables();
        $parameters = $url->getRouteParameters();

        foreach ($route_variables as $variable_name) {
          $parameters[$variable_name] = array_shift($args);
        }

        $url->setRouteParameters($parameters);
      }
      catch (Exception $e) {
        // If the given route doesn't exist, default to <front>
        $url = Url::fromRoute('<front>');
      }
merlinofchaos's avatar
merlinofchaos committed
303
    }
304 305 306 307
    else {
      $url = $view->getUrl($args)->setOptions($url_options);
    }
    $variables['rows'][$id]->url = $url->toString();
308
    $variables['rows'][$id]->count = intval($row->{$argument->count_alias});
309
    $variables['rows'][$id]->attributes = new Attribute($variables['rows'][$id]->attributes);
310
    $variables['rows'][$id]->active = isset($active_urls[$variables['rows'][$id]->url]);
merlinofchaos's avatar
merlinofchaos committed
311 312 313 314
  }
}

/**
315 316 317 318
 * Prepares variables for unformatted summary view templates.
 *
 * Default template: views-view-summary-unformatted.html.twig.
 *
319
 * @param array $variables
320 321 322 323 324 325
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
 *   - options: An array of options. Each option contains:
 *     - separator: A string to be placed between inline fields to keep them
 *       visually distinct.
merlinofchaos's avatar
merlinofchaos committed
326
 */
327
function template_preprocess_views_view_summary_unformatted(&$variables) {
328
  /** @var \Drupal\views\ViewExecutable $view */
329
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
330 331
  $argument = $view->argument[$view->build_info['summary_level']];

332
  $url_options = [];
merlinofchaos's avatar
merlinofchaos committed
333 334 335 336 337 338

  if (!empty($view->exposed_raw_input)) {
    $url_options['query'] = $view->exposed_raw_input;
  }

  $count = 0;
339
  $active_urls = [
340
    // Force system path.
341
    \Drupal::url('<current>', [], ['alias' => TRUE]),
342
    // Could be an alias.
343
    \Drupal::url('<current>'),
344
  ];
345
  $active_urls = array_combine($active_urls, $active_urls);
merlinofchaos's avatar
merlinofchaos committed
346

347 348 349
  // Collect all arguments for each row, to be able to alter them for example
  // by the validator. This is not done per single argument value, because
  // this could cause performance problems.
350
  $row_args = [];
351
  foreach ($variables['rows'] as $id => $row) {
352
    $row_args[$id] = $argument->summaryArgument($row);
merlinofchaos's avatar
merlinofchaos committed
353
  }
354
  $argument->processSummaryArguments($row_args);
merlinofchaos's avatar
merlinofchaos committed
355

356
  foreach ($variables['rows'] as $id => $row) {
357
    // Only false on first time.
merlinofchaos's avatar
merlinofchaos committed
358
    if ($count++) {
359
      $variables['rows'][$id]->separator = Xss::filterAdmin($variables['options']['separator']);
merlinofchaos's avatar
merlinofchaos committed
360
    }
361
    $variables['rows'][$id]->attributes = [];
362
    $variables['rows'][$id]->link = $argument->summaryName($row);
merlinofchaos's avatar
merlinofchaos committed
363 364 365 366 367
    $args = $view->args;
    $args[$argument->position] = $row_args[$id];

    if (!empty($argument->options['summary_options']['base_path'])) {
      $base_path = $argument->options['summary_options']['base_path'];
368 369
      $tokens = $view->getDisplay()->getArgumentsTokens();
      $base_path = $argument->globalTokenReplace($base_path, $tokens);
370 371 372
      // @todo Views should expect and store a leading /. See:
      //   https://www.drupal.org/node/2423913
      $url = Url::fromUserInput('/' . $base_path);
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
      try {
        /** @var \Symfony\Component\Routing\Route $route */
        $route = \Drupal::service('router.route_provider')->getRouteByName($url->getRouteName());
        $route_variables = $route->compile()->getVariables();
        $parameters = $url->getRouteParameters();

        foreach ($route_variables as $variable_name) {
          $parameters[$variable_name] = array_shift($args);
        }

        $url->setRouteParameters($parameters);
      }
      catch (Exception $e) {
        // If the given route doesn't exist, default to <front>
        $url = Url::fromRoute('<front>');
      }
389 390 391
    }
    else {
      $url = $view->getUrl($args)->setOptions($url_options);
merlinofchaos's avatar
merlinofchaos committed
392
    }
393
    $variables['rows'][$id]->url = $url->toString();
394
    $variables['rows'][$id]->count = intval($row->{$argument->count_alias});
395
    $variables['rows'][$id]->active = isset($active_urls[$variables['rows'][$id]->url]);
396
    $variables['rows'][$id]->attributes = new Attribute($variables['rows'][$id]->attributes);
merlinofchaos's avatar
merlinofchaos committed
397 398 399 400
  }
}

/**
401 402 403 404
 * Prepares variables for views table templates.
 *
 * Default template: views-view-table.html.twig.
 *
405
 * @param array $variables
406 407 408
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
merlinofchaos's avatar
merlinofchaos committed
409
 */
410 411
function template_preprocess_views_view_table(&$variables) {
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
412

413
  // We need the raw data for this grouping, which is passed in
414
  // as $variables['rows'].
merlinofchaos's avatar
merlinofchaos committed
415
  // However, the template also needs to use for the rendered fields.  We
416
  // therefore swap the raw data out to a new variable and reset $variables['rows']
merlinofchaos's avatar
merlinofchaos committed
417 418
  // so that it can get rebuilt.
  // Store rows so that they may be used by further preprocess functions.
419
  $result = $variables['result'] = $variables['rows'];
420 421
  $variables['rows'] = [];
  $variables['header'] = [];
merlinofchaos's avatar
merlinofchaos committed
422

423 424
  $options = $view->style_plugin->options;
  $handler = $view->style_plugin;
merlinofchaos's avatar
merlinofchaos committed
425

426
  $fields = &$view->field;
427
  $columns = $handler->sanitizeColumns($options['columns'], $fields);
merlinofchaos's avatar
merlinofchaos committed
428

429 430
  $active = !empty($handler->active) ? $handler->active : '';
  $order = !empty($handler->order) ? $handler->order : 'asc';
merlinofchaos's avatar
merlinofchaos committed
431

432 433 434
  // A boolean variable which stores whether the table has a responsive class.
  $responsive = FALSE;

435 436 437 438 439 440
  // For the actual site we want to not render full URLs, because this would
  // make pagers cacheable per URL, which is problematic in blocks, for example.
  // For the actual live preview though the javascript relies on properly
  // working URLs.
  $route_name = !empty($view->live_preview) ? '<current>' : '<none>';

441
  $query = tablesort_get_query_parameters();
merlinofchaos's avatar
merlinofchaos committed
442 443 444 445
  if (isset($view->exposed_raw_input)) {
    $query += $view->exposed_raw_input;
  }

446 447
  // A boolean to store whether the table's header has any labels.
  $has_header_labels = FALSE;
merlinofchaos's avatar
merlinofchaos committed
448
  foreach ($columns as $field => $column) {
449 450
    // Create a second variable so we can easily find what fields we have and
    // what the CSS classes should be.
451
    $variables['fields'][$field] = Html::cleanCssIdentifier($field);
merlinofchaos's avatar
merlinofchaos committed
452
    if ($active == $field) {
453
      $variables['fields'][$field] .= ' is-active';
merlinofchaos's avatar
merlinofchaos committed
454 455
    }

456
    // Render the header labels.
merlinofchaos's avatar
merlinofchaos committed
457
    if ($field == $column && empty($fields[$field]->options['exclude'])) {
458
      $label = !empty($fields[$field]) ? $fields[$field]->label() : '';
459
      if (empty($options['info'][$field]['sortable']) || !$fields[$field]->clickSortable()) {
460
        $variables['header'][$field]['content'] = $label;
merlinofchaos's avatar
merlinofchaos committed
461 462 463 464 465 466 467 468
      }
      else {
        $initial = !empty($options['info'][$field]['default_sort_order']) ? $options['info'][$field]['default_sort_order'] : 'asc';

        if ($active == $field) {
          $initial = ($order == 'asc') ? 'desc' : 'asc';
        }

469
        $title = t('sort by @s', ['@s' => $label]);
merlinofchaos's avatar
merlinofchaos committed
470
        if ($active == $field) {
471
          $variables['header'][$field]['sort_indicator'] = [
472 473
            '#theme' => 'tablesort_indicator',
            '#style' => $initial,
474
          ];
merlinofchaos's avatar
merlinofchaos committed
475 476 477 478
        }

        $query['order'] = $field;
        $query['sort'] = $initial;
479
        $link_options = [
merlinofchaos's avatar
merlinofchaos committed
480
          'query' => $query,
481
        ];
482
        $url = new Url($route_name, [], $link_options);
483 484 485
        $variables['header'][$field]['url'] = $url->toString();
        $variables['header'][$field]['content'] = $label;
        $variables['header'][$field]['title'] = $title;
merlinofchaos's avatar
merlinofchaos committed
486 487
      }

488
      $variables['header'][$field]['default_classes'] = $fields[$field]->options['element_default_classes'];
merlinofchaos's avatar
merlinofchaos committed
489
      // Set up the header label class.
490
      $variables['header'][$field]['attributes'] = [];
491
      $class = $fields[$field]->elementLabelClasses(0);
merlinofchaos's avatar
merlinofchaos committed
492
      if ($class) {
493
        $variables['header'][$field]['attributes']['class'][] = $class;
merlinofchaos's avatar
merlinofchaos committed
494
      }
495 496
      // Add responsive header classes.
      if (!empty($options['info'][$field]['responsive'])) {
497
        $variables['header'][$field]['attributes']['class'][] = $options['info'][$field]['responsive'];
498 499
        $responsive = TRUE;
      }
500
      // Add a CSS align class to each field if one was set.
merlinofchaos's avatar
merlinofchaos committed
501
      if (!empty($options['info'][$field]['align'])) {
502
        $variables['header'][$field]['attributes']['class'][] = Html::cleanCssIdentifier($options['info'][$field]['align']);
merlinofchaos's avatar
merlinofchaos committed
503 504
      }
      // Add a header label wrapper if one was selected.
505
      if ($variables['header'][$field]['content']) {
506
        $element_label_type = $fields[$field]->elementLabelType(TRUE, TRUE);
merlinofchaos's avatar
merlinofchaos committed
507
        if ($element_label_type) {
508
          $variables['header'][$field]['wrapper_element'] = $element_label_type;
merlinofchaos's avatar
merlinofchaos committed
509
        }
510
        // Improves accessibility of complex tables.
511
        $variables['header'][$field]['attributes']['id'] = Html::getUniqueId('view-' . $field . '-table-column');
merlinofchaos's avatar
merlinofchaos committed
512
      }
513 514 515 516 517 518
      // Check if header label is not empty.
      if (!empty($variables['header'][$field]['content'])) {
        $has_header_labels = TRUE;
      }

      $variables['header'][$field]['attributes'] = new Attribute($variables['header'][$field]['attributes']);
merlinofchaos's avatar
merlinofchaos committed
519 520
    }

521
    // Add a CSS align class to each field if one was set.
merlinofchaos's avatar
merlinofchaos committed
522
    if (!empty($options['info'][$field]['align'])) {
523
      $variables['fields'][$field] .= ' ' . Html::cleanCssIdentifier($options['info'][$field]['align']);
merlinofchaos's avatar
merlinofchaos committed
524 525 526 527
    }

    // Render each field into its appropriate column.
    foreach ($result as $num => $row) {
528 529 530 531 532 533 534 535 536 537

      // Skip building the attributes and content if the field is to be excluded
      // from the display.
      if (!empty($fields[$field]->options['exclude'])) {
        continue;
      }

      // Reference to the column in the loop to make the code easier to read.
      $column_reference =& $variables['rows'][$num]['columns'][$column];

538 539 540 541 542 543
      $column_reference['default_classes'] = $fields[$field]->options['element_default_classes'];

      // Set the field key to the column so it can be used for adding classes
      // in a template.
      $column_reference['fields'][] = $variables['fields'][$field];

544
      // Add field classes.
545
      if (!isset($column_reference['attributes'])) {
546
        $column_reference['attributes'] = [];
547
      }
merlinofchaos's avatar
merlinofchaos committed
548

549
      if ($classes = $fields[$field]->elementClasses($num)) {
550
        $column_reference['attributes']['class'][] = $classes;
merlinofchaos's avatar
merlinofchaos committed
551
      }
552

553 554
      // Add responsive header classes.
      if (!empty($options['info'][$field]['responsive'])) {
555
        $column_reference['attributes']['class'][] = $options['info'][$field]['responsive'];
556 557
      }

558
      // Improves accessibility of complex tables.
559
      if (isset($variables['header'][$field]['attributes']['id'])) {
560
        $column_reference['attributes']['headers'] = [$variables['header'][$field]['attributes']['id']];
561 562
      }

563
      if (!empty($fields[$field])) {
564
        $field_output = $handler->getField($num, $field);
565 566 567
        $column_reference['wrapper_element'] = $fields[$field]->elementType(TRUE, TRUE);
        if (!isset($column_reference['content'])) {
          $column_reference['content'] = [];
merlinofchaos's avatar
merlinofchaos committed
568 569
        }

570
        // Only bother with separators and stuff if the field shows up.
571
        // Place the field into the column, along with an optional separator.
572
        if (trim($field_output) != '') {
573 574 575 576 577
          if (!empty($column_reference['content']) && !empty($options['info'][$column]['separator'])) {
            $column_reference['content'][] = [
              'separator' => ['#markup' => $options['info'][$column]['separator']],
              'field_output' => ['#markup' => $field_output]
            ];
merlinofchaos's avatar
merlinofchaos committed
578
          }
579
          else {
580 581 582
            $column_reference['content'][] = [
              'field_output' => ['#markup' => $field_output]
            ];
583
          }
merlinofchaos's avatar
merlinofchaos committed
584 585
        }
      }
586
      $column_reference['attributes'] = new Attribute($column_reference['attributes']);
merlinofchaos's avatar
merlinofchaos committed
587 588
    }

589 590
    // Remove columns if the "empty_column" option is checked and the
    // field is empty.
merlinofchaos's avatar
merlinofchaos committed
591 592
    if (!empty($options['info'][$field]['empty_column'])) {
      $empty = TRUE;
593
      foreach ($variables['rows'] as $columns) {
594
        $empty &= empty($columns['columns'][$column]['content']);
merlinofchaos's avatar
merlinofchaos committed
595 596
      }
      if ($empty) {
597
        foreach ($variables['rows'] as &$column_items) {
598
          unset($column_items['columns'][$column]);
merlinofchaos's avatar
merlinofchaos committed
599
        }
600
        unset($variables['header'][$column]);
merlinofchaos's avatar
merlinofchaos committed
601 602 603 604 605
      }
    }
  }

  // Hide table header if all labels are empty.
606
  if (!$has_header_labels) {
607
    $variables['header'] = [];
merlinofchaos's avatar
merlinofchaos committed
608 609
  }

610
  foreach ($variables['rows'] as $num => $row) {
611
    $variables['rows'][$num]['attributes'] = [];
612
    if ($row_class = $handler->getRowClass($num)) {
613
      $variables['rows'][$num]['attributes']['class'][] = $row_class;
merlinofchaos's avatar
merlinofchaos committed
614
    }
615
    $variables['rows'][$num]['attributes'] = new Attribute($variables['rows'][$num]['attributes']);
merlinofchaos's avatar
merlinofchaos committed
616 617
  }

618
  if (empty($variables['rows']) && !empty($options['empty_table'])) {
619
    $build = $view->display_handler->renderArea('empty');
620
    $variables['rows'][0]['columns'][0]['content'][0]['field_output'] = $build;
621
    $variables['rows'][0]['attributes'] = new Attribute(['class' => ['odd']]);
merlinofchaos's avatar
merlinofchaos committed
622
    // Calculate the amounts of rows with output.
623
    $variables['rows'][0]['columns'][0]['attributes'] = new Attribute([
624
      'colspan' => count($variables['header']),
625
      'class' => ['views-empty'],
626
    ]);
merlinofchaos's avatar
merlinofchaos committed
627 628
  }

629
  $variables['sticky'] = FALSE;
merlinofchaos's avatar
merlinofchaos committed
630
  if (!empty($options['sticky'])) {
631
    $variables['view']->element['#attached']['library'][] = 'core/drupal.tableheader';
632
    $variables['sticky'] = TRUE;
merlinofchaos's avatar
merlinofchaos committed
633 634
  }

635 636
  // Add the caption to the list if set.
  if (!empty($handler->options['caption'])) {
637
    $variables['caption'] = ['#markup' => $handler->options['caption']];
638
    $variables['caption_needed'] = TRUE;
merlinofchaos's avatar
merlinofchaos committed
639
  }
640 641 642 643
  elseif (!empty($variables['title'])) {
    $variables['caption'] = ['#markup' => $variables['title']];
    $variables['caption_needed'] = TRUE;
  }
644
  else {
645 646
    $variables['caption'] = '';
    $variables['caption_needed'] = FALSE;
647 648
  }

649 650 651
  $variables['summary'] = $handler->options['summary'];
  $variables['description'] = $handler->options['description'];
  $variables['caption_needed'] |= !empty($variables['summary']) || !empty($variables['description']);
652

653
  $variables['responsive'] = FALSE;
654 655 656
  // If the table has headers and it should react responsively to columns hidden
  // with the classes represented by the constants RESPONSIVE_PRIORITY_MEDIUM
  // and RESPONSIVE_PRIORITY_LOW, add the tableresponsive behaviors.
657
  if (isset($variables['header']) && $responsive) {
658
    $variables['view']->element['#attached']['library'][] = 'core/drupal.tableresponsive';
659 660
    // Add 'responsive-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
661
    $variables['responsive'] = TRUE;
662
  }
merlinofchaos's avatar
merlinofchaos committed
663 664 665
}

/**
666 667 668 669
 * Prepares variables for views grid style templates.
 *
 * Default template: views-view-grid.html.twig.
 *
670
 * @param array $variables
671 672 673
 *   An associative array containing:
 *   - view: The view object.
 *   - rows: An array of row items. Each row is an array of content.
merlinofchaos's avatar
merlinofchaos committed
674
 */
675
function template_preprocess_views_view_grid(&$variables) {
676 677 678 679 680
  $options = $variables['options'] = $variables['view']->style_plugin->options;
  $horizontal = ($options['alignment'] === 'horizontal');

  $col = 0;
  $row = 0;
681
  $items = [];
682 683 684 685
  $remainders = count($variables['rows']) % $options['columns'];
  $num_rows = floor(count($variables['rows']) / $options['columns']);

  // Iterate over each rendered views result row.
686
  foreach ($variables['rows'] as $result_index => $item) {
687 688 689 690 691 692 693 694

    // Add the item.
    if ($horizontal) {
      $items[$row]['content'][$col]['content'] = $item;
    }
    else {
      $items[$col]['content'][$row]['content'] = $item;
    }
merlinofchaos's avatar
merlinofchaos committed
695

696 697
    // Create attributes for rows.
    if (!$horizontal || ($horizontal && empty($items[$row]['attributes']))) {
698
      $row_attributes = ['class' => []];
699
      // Add custom row classes.
700
      $row_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'row')));
701 702 703 704 705 706 707 708 709
      if (!empty($row_class)) {
        $row_attributes['class'] = array_merge($row_attributes['class'], $row_class);
      }
      // Add row attributes to the item.
      if ($horizontal) {
        $items[$row]['attributes'] = new Attribute($row_attributes);
      }
      else {
        $items[$col]['content'][$row]['attributes'] = new Attribute($row_attributes);
merlinofchaos's avatar
merlinofchaos committed
710 711
      }
    }
712 713 714

    // Create attributes for columns.
    if ($horizontal || (!$horizontal && empty($items[$col]['attributes']))) {
715
      $col_attributes = ['class' => []];
716 717
      // Add default views column classes.
      // Add custom column classes.
718
      $col_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'col')));
719 720 721 722 723 724 725 726 727 728 729 730 731 732
      if (!empty($col_class)) {
        $col_attributes['class'] = array_merge($col_attributes['class'], $col_class);
      }
      // Add automatic width for columns.
      if ($options['automatic_width']) {
        $col_attributes['style'] = 'width: ' . (100 / $options['columns']) . '%;';
      }
      // Add column attributes to the item.
      if ($horizontal) {
        $items[$row]['content'][$col]['attributes'] = new Attribute($col_attributes);
      }
      else {
        $items[$col]['attributes'] = new Attribute($col_attributes);
      }
merlinofchaos's avatar
merlinofchaos committed
733 734
    }

735 736 737 738 739 740 741 742 743 744 745 746 747 748 749
    // Increase, decrease or reset appropriate integers.
    if ($horizontal) {
      if ($col == 0 && $col != ($options['columns'] - 1)) {
        $col++;
      }
      elseif ($col >= ($options['columns'] - 1)) {
        $col = 0;
        $row++;
      }
      else {
        $col++;
      }
    }
    else {
      $row++;
merlinofchaos's avatar
merlinofchaos committed
750 751 752 753 754 755 756 757 758 759 760 761
      if (!$remainders && $row == $num_rows) {
        $row = 0;
        $col++;
      }
      elseif ($remainders && $row == $num_rows + 1) {
        $row = 0;
        $col++;
        $remainders--;
      }
    }
  }

762 763
  // Add items to the variables array.
  $variables['items'] = $items;
merlinofchaos's avatar
merlinofchaos committed
764 765 766
}

/**
767 768 769 770
 * Prepares variables for views unformatted rows templates.
 *
 * Default template: views-view-unformatted.html.twig.
 *
771
 * @param array $variables
772 773 774
 *   An associative array containing:
 *   - view: The view object.
 *   - rows: An array of row items. Each row is an array of content.
merlinofchaos's avatar
merlinofchaos committed
775
 */
776 777 778
function template_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
merlinofchaos's avatar
merlinofchaos committed
779 780 781
  $style = $view->style_plugin;
  $options = $style->options;

782
  $variables['default_row_class'] = !empty($options['default_row_class']);
merlinofchaos's avatar
merlinofchaos committed
783
  foreach ($rows as $id => $row) {
784
    $variables['rows'][$id] = [];
785
    $variables['rows'][$id]['content'] = $row;
786
    $variables['rows'][$id]['attributes'] = new Attribute();
787
    if ($row_class = $view->style_plugin->getRowClass($id)) {
788
      $variables['rows'][$id]['attributes']->addClass($row_class);
merlinofchaos's avatar
merlinofchaos committed
789 790 791 792 793
    }
  }
}

/**
794 795 796 797 798 799 800
 * Prepares variables for Views HTML list templates.
 *
 * Default template: views-view-list.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - view: A View object.
merlinofchaos's avatar
merlinofchaos committed
801
 */
802 803
function template_preprocess_views_view_list(&$variables) {
  $handler  = $variables['view']->style_plugin;
merlinofchaos's avatar
merlinofchaos committed
804

805
  // Fetch classes from handler options.
806 807
  if ($handler->options['class']) {
    $class = explode(' ', $handler->options['class']);
808
    $class = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $class);
merlinofchaos's avatar
merlinofchaos committed
809

810
    // Initialize a new attribute class for $class.
811
    $variables['list']['attributes'] = new Attribute(['class' => $class]);
812
  }
merlinofchaos's avatar
merlinofchaos committed
813

814 815 816
  // Fetch wrapper classes from handler options.
  if ($handler->options['wrapper_class']) {
    $wrapper_class = explode(' ', $handler->options['wrapper_class']);
817
    $variables['attributes']['class'] = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $wrapper_class);
818 819
  }

820
  $variables['list']['type'] = $handler->options['type'];
821

822
  template_preprocess_views_view_unformatted($variables);
merlinofchaos's avatar
merlinofchaos committed
823 824 825
}

/**
826 827 828 829
 * Prepares variables for RSS feed templates.
 *
 * Default template: views-view-rss.html.twig.
 *
830
 * @param array $variables
831 832 833
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
834
 */
835
function template_preprocess_views_view_rss(&$variables) {
836
  $view  = $variables['view'];
837
  $items = $variables['rows'];
838
  $style = $view->style_plugin;
merlinofchaos's avatar
merlinofchaos committed
839

840
  $config = \Drupal::config('system.site');
841

merlinofchaos's avatar
merlinofchaos committed
842 843 844
  // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  // We strip all HTML tags, but need to prevent double encoding from properly
  // escaped source data (such as &amp becoming &amp;amp;).
845
  $variables['description'] = Html::decodeEntities(strip_tags($style->getDescription()));
merlinofchaos's avatar
merlinofchaos committed
846

847
  if ($view->display_handler->getOption('sitename_title')) {
848
    $title = $config->get('name');
849
    if ($slogan = $config->get('slogan')) {
merlinofchaos's avatar
merlinofchaos committed
850 851 852 853
      $title .= ' - ' . $slogan;
    }
  }
  else {
854
    $title = $view->getTitle();
merlinofchaos's avatar
merlinofchaos committed
855
  }
856
  $variables['title'] = $title;
merlinofchaos's avatar
merlinofchaos committed
857

858 859
  // Figure out which display which has a path we're using for this feed. If
  // there isn't one, use the global $base_url
860
  $link_display_id = $view->display_handler->getLinkDisplay();
861
  if ($link_display_id && $display = $view->displayHandlers->get($link_display_id)) {
862
    $url = $view->getUrl(NULL, $link_display_id);
merlinofchaos's avatar
merlinofchaos committed
863 864
  }

865 866
  /** @var \Drupal\Core\Url $url */
  if ($url) {
867
    $url_options = ['absolute' => TRUE];
merlinofchaos's avatar
merlinofchaos committed
868 869 870 871
    if (!empty($view->exposed_raw_input)) {
      $url_options['query'] = $view->exposed_raw_input;
    }

872 873
    // Compare the link to the default home page; if it's the default home page,
    // just use $base_url.
874
    $url_string = $url->setOptions($url_options)->toString();
875
    if ($url_string === Url::fromUserInput($config->get('page.front'))->toString()) {
876
      $url_string = Url::fromRoute('<front>')->setAbsolute()->toString();
merlinofchaos's avatar
merlinofchaos committed
877 878
    }

879
    $variables['link'] = $url_string;
merlinofchaos's avatar
merlinofchaos committed
880 881
  }

882
  $variables['langcode'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
883 884
  $variables['namespaces'] = new Attribute($style->namespaces);
  $variables['items'] = $items;
885
  $variables['channel_elements'] = \Drupal::service('renderer')->render($style->channel_elements);
merlinofchaos's avatar
merlinofchaos committed
886 887 888

  // During live preview we don't want to output the header since the contents
  // of the feed are being displayed inside a normal HTML page.
889 890
  if (empty($variables['view']->live_preview)) {
    $variables['view']->getResponse()->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
merlinofchaos's avatar
merlinofchaos committed
891 892 893 894
  }
}

/**
895 896 897 898
 * Prepares variables for views RSS item templates.
 *
 * Default template: views-view-row-rss.html.twig.
 *
899
 * @param array $variables
900 901
 *   An associative array containing:
 *   - row: The raw results rows.
merlinofchaos's avatar
merlinofchaos committed
902
 */
903 904
function template_preprocess_views_view_row_rss(&$variables) {
  $item = $variables['row'];
905
  $variables['title'] = $item->title;
906
  $variables['link'] = $item->link;
907

908 909 910 911 912 913 914 915
  // The description is the only place where we should find HTML.
  // @see https://validator.w3.org/feed/docs/rss2.html#hrelementsOfLtitemgt
  // If we have a render array, render it here and pass the result to the
  // template, letting Twig autoescape it.
  if (isset($item->description) && is_array($item->description)) {
    $variables['description'] = (string) \Drupal::service('renderer')->render($item->description);
  }

916
  $variables['item_elements'] = [];
917 918 919 920 921 922
  foreach ($item->elements as $element) {
    if (isset($element['attributes']) && is_array($element['attributes'])) {
      $element['attributes'] = new Attribute($element['attributes']);
    }
    $variables['item_elements'][] = $element;
  }
merlinofchaos's avatar
merlinofchaos committed
923 924
}

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949
/**
 * Prepares variables for OPML feed templates.
 *
 * Default template: views-view-opml.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
 */
function template_preprocess_views_view_opml(&$variables) {
  $view  = $variables['view'];
  $items = $variables['rows'];

  $config = \Drupal::config('system.site');

  if ($view->display_handler->getOption('sitename_title')) {
    $title = $config->get('name');
    if ($slogan = $config->get('slogan')) {
      $title .= ' - ' . $slogan;
    }
  }
  else {
    $title = $view->getTitle();
  }
950
  $variables['title'] = $title;
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
  $variables['items'] = $items;
  $variables['updated'] = gmdate(DATE_RFC2822, REQUEST_TIME);

  // During live preview we don't want to output the header since the contents
  // of the feed are being displayed inside a normal HTML page.
  if (empty($variables['view']->live_preview)) {
    $variables['view']->getResponse()->headers->set('Content-Type', 'text/xml; charset=utf-8');
  }
}

/**
 * Prepares variables for views OPML item templates.
 *
 * Default template: views-view-row-opml.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - row: The raw results rows.
 */
function template_preprocess_views_view_row_opml(&$variables) {
  $item = $variables['row'];

  $variables['attributes'] = new Attribute($item);
}

merlinofchaos's avatar
merlinofchaos committed
976
/**
977 978 979 980
 * Prepares variables for views exposed form templates.
 *
 * Default template: views-exposed-form.html.twig.
 *
981
 * @param array $variables
982 983
 *   An associative array containing:
 *   - form: A render element representing the form.
merlinofchaos's avatar
merlinofchaos committed
984
 */
985 986
function template_preprocess_views_exposed_form(&$variables) {
  $form = &$variables['form'];
merlinofchaos's avatar
merlinofchaos committed
987 988

  if (!empty($form['q'])) {
989
    $variables['q'] = $form['q'];
merlinofchaos's avatar
merlinofchaos committed
990 991
  }

992
  foreach ($form['#info'] as $info) {
merlinofchaos's avatar
merlinofchaos committed
993
    if (!empty($info['label'])) {
994
      $form[$info['value']]['#title'] = $info['label'];
merlinofchaos's avatar
merlinofchaos committed
995
    }
996 997 998
    if (!empty($info['description'])) {
      $form[$info['value']]['#description'] = $info['description'];
    }
merlinofchaos's avatar
merlinofchaos committed
999 1000 1001
  }
}

1002
/**
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
 * Prepares variables for views mini-pager templates.
 *
 * Default template: views-mini-pager.html.twig.
 *
 * @param array $variables
 *   An associative array containing:
 *   - tags: Provides link text for the next/previous links.
 *   - element: The pager's id.
 *   - parameters: Any extra GET parameters that should be retained, such as
 *     exposed input.
1013
 */