views.theme.inc 38.6 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\SafeMarkup;
10
use Drupal\Component\Utility\Xss;
11
use Drupal\Core\Template\Attribute;
12
use Drupal\Core\Url;
13

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

27 28
  $variables['css_name'] = Html::cleanCssIdentifier($id);
  $variables['id'] = $id;
29
  $variables['display_id'] = $view->current_display;
30 31 32 33 34
  // 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
35

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

  // Attachments are always updated with the outer view, never by themselves,
  // so they do not have dom ids.
  if (empty($view->is_attachment)) {
45 46
    // Our JavaScript needs to have some means to find the HTML belonging to
    // this view.
merlinofchaos's avatar
merlinofchaos committed
47 48 49 50
    //
    // 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
51 52
    // 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
53
    // drupalSettings and the DIV wrapper.
54
    $variables['dom_id'] = $view->dom_id;
merlinofchaos's avatar
merlinofchaos committed
55 56 57 58
  }
}

/**
59 60 61 62
 * Prepares variables for views fields templates.
 *
 * Default template: views-view-fields.html.twig.
 *
63
 * @param array $variables
64 65 66 67 68 69 70 71 72 73 74 75
 *   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
76
 */
77 78
function template_preprocess_views_view_fields(&$variables) {
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
79 80 81

  // Loop through the fields for this view.
  $previous_inline = FALSE;
82
  $variables['fields'] = array(); // ensure it's at least an empty array.
83 84
  /** @var \Drupal\views\ResultRow $row */
  $row = $variables['row'];
merlinofchaos's avatar
merlinofchaos committed
85 86
  foreach ($view->field as $id => $field) {
    // render this even if set to exclude so it can be used elsewhere.
87
    $field_output = $view->style_plugin->getField($row->index, $id);
88
    $empty = $field->isValueEmpty($field_output, $field->options['empty_zero']);
89
    if (empty($field->options['exclude']) && (!$empty || (empty($field->options['hide_empty']) && empty($variables['options']['hide_empty'])))) {
merlinofchaos's avatar
merlinofchaos committed
90
      $object = new stdClass();
91
      $object->handler = $view->field[$id];
92
      $object->inline = !empty($variables['options']['inline'][$id]);
merlinofchaos's avatar
merlinofchaos committed
93

94
      $object->element_type = $object->handler->elementType(TRUE, !$variables['options']['default_field_elements'], $object->inline);
merlinofchaos's avatar
merlinofchaos committed
95
      if ($object->element_type) {
96
        $attributes = array();
merlinofchaos's avatar
merlinofchaos committed
97
        if ($object->handler->options['element_default_classes']) {
98
          $attributes['class'][] = 'field-content';
merlinofchaos's avatar
merlinofchaos committed
99 100
        }

101
        if ($classes = $object->handler->elementClasses($row->index)) {
102
          $attributes['class'][] = $classes;
merlinofchaos's avatar
merlinofchaos committed
103
        }
104
        $attributes = new Attribute($attributes);
merlinofchaos's avatar
merlinofchaos committed
105 106

        $pre = '<' . $object->element_type;
107
        $pre .= $attributes;
merlinofchaos's avatar
merlinofchaos committed
108 109 110
        $field_output = $pre . '>' . $field_output . '</' . $object->element_type . '>';
      }

111 112 113
      // Protect ourselves somewhat for backward compatibility. This will
      // prevent old templates from producing invalid HTML when no element type
      // is selected.
merlinofchaos's avatar
merlinofchaos committed
114 115 116 117 118
      if (empty($object->element_type)) {
        $object->element_type = 'span';
      }

      $object->content = $field_output;
119 120
      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
121 122 123 124 125
      }
      else {
        $object->raw = NULL; // make sure it exists to reduce NOTICE
      }

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

130
      $object->class = Html::cleanCssIdentifier($id);
merlinofchaos's avatar
merlinofchaos committed
131 132

      $previous_inline = $object->inline;
133
      $object->inline_html = $object->handler->elementWrapperType(TRUE, TRUE);
134
      if ($object->inline_html === '' && $variables['options']['default_field_elements']) {
merlinofchaos's avatar
merlinofchaos committed
135 136 137 138 139 140 141 142
        $object->inline_html = $object->inline ? 'span' : 'div';
      }

      // Set up the wrapper HTML.
      $object->wrapper_prefix = '';
      $object->wrapper_suffix = '';

      if ($object->inline_html) {
143
        $attributes = array();
merlinofchaos's avatar
merlinofchaos committed
144
        if ($object->handler->options['element_default_classes']) {
145 146
          $attributes['class'][] = 'views-field';
          $attributes['class'][] = 'views-field-' . $object->class;
merlinofchaos's avatar
merlinofchaos committed
147 148
        }

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

        $object->wrapper_prefix = '<' . $object->inline_html;
155
        $object->wrapper_prefix .= $attributes;
merlinofchaos's avatar
merlinofchaos committed
156 157 158 159 160 161
        $object->wrapper_prefix .= '>';
        $object->wrapper_suffix = '</' . $object->inline_html . '>';
      }

      // Set up the label for the value and the HTML to make it easier
      // on the template.
162
      $object->label = SafeMarkup::checkPlain($view->field[$id]->label());
merlinofchaos's avatar
merlinofchaos committed
163 164 165 166 167 168 169
      $object->label_html = '';
      if ($object->label) {
        $object->label_html .= $object->label;
        if ($object->handler->options['element_label_colon']) {
          $object->label_html .= ': ';
        }

170
        $object->elementLabelType = $object->handler->elementLabelType(TRUE, !$variables['options']['default_field_elements']);
171
        if ($object->elementLabelType) {
172
          $attributes = array();
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
          $element_label_class = $object->handler->elementLabelClasses($row->index);
merlinofchaos's avatar
merlinofchaos committed
179
          if ($element_label_class) {
180
            $attributes['class'][] = $element_label_class;
merlinofchaos's avatar
merlinofchaos committed
181
          }
182
          $attributes = new Attribute($attributes);
merlinofchaos's avatar
merlinofchaos committed
183

184
          $pre = '<' . $object->elementLabelType;
185
          $pre .= $attributes;
merlinofchaos's avatar
merlinofchaos committed
186 187
          $pre .= '>';

188
          $object->label_html = $pre . $object->label_html . '</' . $object->elementLabelType . '>';
merlinofchaos's avatar
merlinofchaos committed
189 190 191
        }
      }

192
      $variables['fields'][$id] = $object;
merlinofchaos's avatar
merlinofchaos committed
193 194 195 196 197
    }
  }

}

198
/**
199 200 201 202 203 204 205 206 207 208 209 210
 * Returns HTML for multiple views fields.
 *
 * @param $variables
 *   An associative array containing:
 *   - fields: An array of field objects. Each field object contains:
 *     - separator: A string that separates the fields.
 *     - wrapper_suffix: A string added to the beginning of the fields.
 *     - label_html: An HTML string that labels the fields.
 *     - content: The fields.
 *     - wrapper_suffix: A string added to the end of the fields.
 *
 * @see template_preprocess_views_view_fields()
211 212
 *
 * @ingroup themeable
213
 */
214 215 216 217
function theme_views_view_fields($variables) {
  $fields = $variables['fields'];
  $output = '';

218
  foreach ($fields as $field) {
219 220 221 222 223 224 225 226 227 228 229 230 231 232
    if (!empty($field->separator)) {
      $output .= $field->separator;
    }

    $output .= $field->wrapper_prefix;
    $output .= $field->label_html;
    $output .= $field->content;

    $output .= $field->wrapper_suffix;
  }

  return $output;
}

merlinofchaos's avatar
merlinofchaos committed
233
/**
234 235 236 237
 * Prepares variables for views single grouping templates.
 *
 * Default template: views-view-grouping.html.twig.
 *
238
 * @param array $variables
239 240 241 242 243 244 245
 *   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.
246
 */
247 248
function template_preprocess_views_view_grouping(&$variables) {
  $variables['content'] = $variables['view']->style_plugin->renderGroupingSets($variables['rows'], $variables['grouping_level']);
merlinofchaos's avatar
merlinofchaos committed
249 250 251 252 253 254 255 256
}

/**
 * Display a single views field.
 *
 * Interesting bits of info:
 * $field->field_alias says what the raw value in $row will be. Reach it like
 * this: @code { $row->{$field->field_alias} @endcode
257 258
 *
 * @ingroup themeable
merlinofchaos's avatar
merlinofchaos committed
259
 */
260 261
function theme_views_view_field($variables) {
  return $variables['output'];
merlinofchaos's avatar
merlinofchaos committed
262 263 264
}

/**
265
 * Prepares variables for views field templates.
merlinofchaos's avatar
merlinofchaos committed
266
 *
267 268
 * Default template: views-view-field.html.twig.
 *
269
 * @param array $variables
270 271 272 273 274
 *   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
275
 */
276 277
function template_preprocess_views_view_field(&$variables) {
  $variables['output'] = $variables['field']->advancedRender($variables['row']);
merlinofchaos's avatar
merlinofchaos committed
278 279 280
}

/**
281 282 283 284 285 286
 * Prepares variables for views summary templates.
 *
 * The summary prints a single record from a row, with fields.
 *
 * Default template: views-view-summary.html.twig.
 *
287
 * @param array $variables
288 289 290
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
merlinofchaos's avatar
merlinofchaos committed
291
 */
292
function template_preprocess_views_view_summary(&$variables) {
293
  /** @var \Drupal\views\ViewExecutable $view */
294
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
295 296 297 298 299 300 301 302
  $argument = $view->argument[$view->build_info['summary_level']];

  $url_options = array();

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

303
  $active_urls = array(
304 305
    // Force system path.
    \Drupal::url('<current>', [], ['alias' => TRUE]),
306 307
    // Force system path.
    Url::fromRouteMatch(\Drupal::routeMatch())->setOption('alias', TRUE)->toString(),
308 309
    // Could be an alias.
    \Drupal::url('<current>'),
310 311
    // Could be an alias.
    Url::fromRouteMatch(\Drupal::routeMatch())->toString(),
312 313
  );
  $active_urls = array_combine($active_urls, $active_urls);
merlinofchaos's avatar
merlinofchaos committed
314

315 316 317
  // 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.
merlinofchaos's avatar
merlinofchaos committed
318 319
  $row_args = array();

320
  foreach ($variables['rows'] as $id => $row) {
321
    $row_args[$id] = $argument->summaryArgument($row);
merlinofchaos's avatar
merlinofchaos committed
322
  }
323
  $argument->processSummaryArguments($row_args);
merlinofchaos's avatar
merlinofchaos committed
324

325
  foreach ($variables['rows'] as $id => $row) {
326
    $variables['rows'][$id]->attributes = array();
327
    $variables['rows'][$id]->link = $argument->summaryName($row);
merlinofchaos's avatar
merlinofchaos committed
328 329 330 331 332
    $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'];
333 334
      $tokens = $this->getArgumentsTokens();
      $base_path = $this->viewsTokenReplace($base_path, $tokens);
335 336 337
      // @todo Views should expect and store a leading /. See:
      //   https://www.drupal.org/node/2423913
      $url = Url::fromUserInput('/' . $base_path);
merlinofchaos's avatar
merlinofchaos committed
338
    }
339 340 341 342
    else {
      $url = $view->getUrl($args)->setOptions($url_options);
    }
    $variables['rows'][$id]->url = $url->toString();
343
    $variables['rows'][$id]->count = intval($row->{$argument->count_alias});
344
    $variables['rows'][$id]->attributes = new Attribute($variables['rows'][$id]->attributes);
345
    $variables['rows'][$id]->active = isset($active_urls[$variables['rows'][$id]->url]);
merlinofchaos's avatar
merlinofchaos committed
346 347 348 349
  }
}

/**
350 351 352 353
 * Prepares variables for unformatted summary view templates.
 *
 * Default template: views-view-summary-unformatted.html.twig.
 *
354
 * @param array $variables
355 356 357 358 359 360
 *   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
361
 */
362 363
function template_preprocess_views_view_summary_unformatted(&$variables) {
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
364 365 366 367 368 369 370 371 372
  $argument = $view->argument[$view->build_info['summary_level']];

  $url_options = array();

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

  $count = 0;
373
  $active_urls = array(
374
    // Force system path.
375
    \Drupal::url('<current>', [], ['alias' => TRUE]),
376
    // Could be an alias.
377
    \Drupal::url('<current>'),
378 379
  );
  $active_urls = array_combine($active_urls, $active_urls);
merlinofchaos's avatar
merlinofchaos committed
380

381 382 383
  // 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.
merlinofchaos's avatar
merlinofchaos committed
384
  $row_args = array();
385
  foreach ($variables['rows'] as $id => $row) {
386
    $row_args[$id] = $argument->summaryArgument($row);
merlinofchaos's avatar
merlinofchaos committed
387
  }
388
  $argument->processSummaryArguments($row_args);
merlinofchaos's avatar
merlinofchaos committed
389

390
  foreach ($variables['rows'] as $id => $row) {
391
    // Only false on first time.
merlinofchaos's avatar
merlinofchaos committed
392
    if ($count++) {
393
      $variables['rows'][$id]->separator = Xss::filterAdmin($variables['options']['separator']);
merlinofchaos's avatar
merlinofchaos committed
394
    }
395
    $variables['rows'][$id]->attributes = array();
396
    $variables['rows'][$id]->link = $argument->summaryName($row);
merlinofchaos's avatar
merlinofchaos committed
397 398 399 400 401
    $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'];
402 403
      $tokens = $this->getArgumentsTokens();
      $base_path = $this->viewsTokenReplace($base_path, $tokens);
404 405 406
      // @todo Views should expect and store a leading /. See:
      //   https://www.drupal.org/node/2423913
      $url = Url::fromUserInput('/' . $base_path);
407 408 409
    }
    else {
      $url = $view->getUrl($args)->setOptions($url_options);
merlinofchaos's avatar
merlinofchaos committed
410
    }
411
    $variables['rows'][$id]->url = $url->toString();
412
    $variables['rows'][$id]->count = intval($row->{$argument->count_alias});
413
    $variables['rows'][$id]->active = isset($active_urls[$variables['rows'][$id]->url]);
414
    $variables['rows'][$id]->attributes = new Attribute($variables['rows'][$id]->attributes);
merlinofchaos's avatar
merlinofchaos committed
415 416 417 418
  }
}

/**
419 420 421 422
 * Prepares variables for views table templates.
 *
 * Default template: views-view-table.html.twig.
 *
423
 * @param array $variables
424 425 426
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
merlinofchaos's avatar
merlinofchaos committed
427
 */
428 429
function template_preprocess_views_view_table(&$variables) {
  $view = $variables['view'];
merlinofchaos's avatar
merlinofchaos committed
430

431
  // We need the raw data for this grouping, which is passed in
432
  // as $variables['rows'].
merlinofchaos's avatar
merlinofchaos committed
433
  // However, the template also needs to use for the rendered fields.  We
434
  // therefore swap the raw data out to a new variable and reset $variables['rows']
merlinofchaos's avatar
merlinofchaos committed
435 436
  // so that it can get rebuilt.
  // Store rows so that they may be used by further preprocess functions.
437 438 439
  $result = $variables['result'] = $variables['rows'];
  $variables['rows'] = array();
  $variables['header'] = array();
merlinofchaos's avatar
merlinofchaos committed
440

441 442
  $options = $view->style_plugin->options;
  $handler = $view->style_plugin;
merlinofchaos's avatar
merlinofchaos committed
443

444
  $fields = &$view->field;
445
  $columns = $handler->sanitizeColumns($options['columns'], $fields);
merlinofchaos's avatar
merlinofchaos committed
446

447 448
  $active = !empty($handler->active) ? $handler->active : '';
  $order = !empty($handler->order) ? $handler->order : 'asc';
merlinofchaos's avatar
merlinofchaos committed
449

450 451 452
  // A boolean variable which stores whether the table has a responsive class.
  $responsive = FALSE;

453
  $query = tablesort_get_query_parameters();
merlinofchaos's avatar
merlinofchaos committed
454 455 456 457
  if (isset($view->exposed_raw_input)) {
    $query += $view->exposed_raw_input;
  }

458 459
  // A boolean to store whether the table's header has any labels.
  $has_header_labels = FALSE;
merlinofchaos's avatar
merlinofchaos committed
460
  foreach ($columns as $field => $column) {
461 462
    // Create a second variable so we can easily find what fields we have and
    // what the CSS classes should be.
463
    $variables['fields'][$field] = Html::cleanCssIdentifier($field);
merlinofchaos's avatar
merlinofchaos committed
464
    if ($active == $field) {
465
      $variables['fields'][$field] .= ' is-active';
merlinofchaos's avatar
merlinofchaos committed
466 467
    }

468
    // Render the header labels.
merlinofchaos's avatar
merlinofchaos committed
469
    if ($field == $column && empty($fields[$field]->options['exclude'])) {
470
      $label = SafeMarkup::checkPlain(!empty($fields[$field]) ? $fields[$field]->label() : '');
471
      if (empty($options['info'][$field]['sortable']) || !$fields[$field]->clickSortable()) {
472
        $variables['header'][$field]['content'] = $label;
merlinofchaos's avatar
merlinofchaos committed
473 474 475 476 477 478 479 480 481 482
      }
      else {
        $initial = !empty($options['info'][$field]['default_sort_order']) ? $options['info'][$field]['default_sort_order'] : 'asc';

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

        $title = t('sort by @s', array('@s' => $label));
        if ($active == $field) {
483 484 485 486
          $tablesort_indicator = array(
            '#theme' => 'tablesort_indicator',
            '#style' => $initial,
          );
487 488
          $markup = drupal_render($tablesort_indicator);
          $label = SafeMarkup::set($label . $markup);
merlinofchaos's avatar
merlinofchaos committed
489 490 491 492 493 494 495 496
        }

        $query['order'] = $field;
        $query['sort'] = $initial;
        $link_options = array(
          'attributes' => array('title' => $title),
          'query' => $query,
        );
497
        $variables['header'][$field]['content'] = \Drupal::l($label, new Url('<current>', [], $link_options));
merlinofchaos's avatar
merlinofchaos committed
498 499
      }

500
      $variables['header'][$field]['default_classes'] = $fields[$field]->options['element_default_classes'];
merlinofchaos's avatar
merlinofchaos committed
501
      // Set up the header label class.
502
      $variables['header'][$field]['attributes'] = array();
503
      $class = $fields[$field]->elementLabelClasses(0);
merlinofchaos's avatar
merlinofchaos committed
504
      if ($class) {
505
        $variables['header'][$field]['attributes']['class'][] = $class;
merlinofchaos's avatar
merlinofchaos committed
506
      }
507 508
      // Add responsive header classes.
      if (!empty($options['info'][$field]['responsive'])) {
509
        $variables['header'][$field]['attributes']['class'][] = $options['info'][$field]['responsive'];
510 511
        $responsive = TRUE;
      }
512
      // Add a CSS align class to each field if one was set.
merlinofchaos's avatar
merlinofchaos committed
513
      if (!empty($options['info'][$field]['align'])) {
514
        $variables['header'][$field]['attributes']['class'][] = Html::cleanCssIdentifier($options['info'][$field]['align']);
merlinofchaos's avatar
merlinofchaos committed
515 516
      }
      // Add a header label wrapper if one was selected.
517
      if ($variables['header'][$field]['content']) {
518
        $element_label_type = $fields[$field]->elementLabelType(TRUE, TRUE);
merlinofchaos's avatar
merlinofchaos committed
519
        if ($element_label_type) {
520
          $variables['header'][$field]['content'] = '<' . $element_label_type . '>' . $variables['header'][$field]['content'] . '</' . $element_label_type . '>';
merlinofchaos's avatar
merlinofchaos committed
521
        }
522
        // Improves accessibility of complex tables.
523
        $variables['header'][$field]['attributes']['id'] = Html::getUniqueId('view-' . $field . '-table-column');
merlinofchaos's avatar
merlinofchaos committed
524
      }
525 526 527 528 529 530
      // 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
531 532
    }

533
    // Add a CSS align class to each field if one was set.
merlinofchaos's avatar
merlinofchaos committed
534
    if (!empty($options['info'][$field]['align'])) {
535
      $variables['fields'][$field] .= ' ' . Html::cleanCssIdentifier($options['info'][$field]['align']);
merlinofchaos's avatar
merlinofchaos committed
536 537 538 539
    }

    // Render each field into its appropriate column.
    foreach ($result as $num => $row) {
540 541 542 543 544 545 546 547 548 549

      // 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];

550 551 552 553 554 555
      $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];

556
      // Add field classes.
557 558 559
      if (!isset($column_reference['attributes'])) {
        $column_reference['attributes'] = array();
      }
merlinofchaos's avatar
merlinofchaos committed
560

561
      if ($classes = $fields[$field]->elementClasses($num)) {
562
        $column_reference['attributes']['class'][] = $classes;
merlinofchaos's avatar
merlinofchaos committed
563
      }
564

565 566
      // Add responsive header classes.
      if (!empty($options['info'][$field]['responsive'])) {
567
        $column_reference['attributes']['class'][] = $options['info'][$field]['responsive'];
568 569
      }

570
      // Improves accessibility of complex tables.
571
      if (isset($variables['header'][$field]['attributes']['id'])) {
572
        $column_reference['attributes']['headers'] = array($variables['header'][$field]['attributes']['id']);
573 574
      }

575
      if (!empty($fields[$field])) {
576
        $field_output = $handler->getField($num, $field);
577
        $element_type = $fields[$field]->elementType(TRUE, TRUE);
merlinofchaos's avatar
merlinofchaos committed
578
        if ($element_type) {
579
          $field_output = SafeMarkup::set('<' . $element_type . '>' .  SafeMarkup::escape($field_output) . '</' . $element_type . '>');
merlinofchaos's avatar
merlinofchaos committed
580 581
        }

582
        // Only bother with separators and stuff if the field shows up.
583
        if (!empty($field_output)) {
584
          // Place the field into the column, along with an optional separator.
585
          if (!empty($column_reference['content'])) {
586
            if (!empty($options['info'][$column]['separator'])) {
587 588 589
              $safe_content = SafeMarkup::escape($column_reference['content']);
              $safe_separator = Xss::filterAdmin($options['info'][$column]['separator']);
              $column_reference['content'] = SafeMarkup::set($safe_content . $safe_separator);
590
            }
merlinofchaos's avatar
merlinofchaos committed
591
          }
592
          else {
593
            $column_reference['content'] = '';
594
          }
595 596 597
          $safe_content = SafeMarkup::escape($column_reference['content']);
          $safe_field_output = SafeMarkup::escape($field_output);
          $column_reference['content'] = SafeMarkup::set($safe_content . $safe_field_output);
merlinofchaos's avatar
merlinofchaos committed
598 599
        }
      }
600
      $column_reference['attributes'] = new Attribute($column_reference['attributes']);
merlinofchaos's avatar
merlinofchaos committed
601 602
    }

603 604
    // Remove columns if the option is hide empty column is checked and the
    // field is not empty.
merlinofchaos's avatar
merlinofchaos committed
605 606
    if (!empty($options['info'][$field]['empty_column'])) {
      $empty = TRUE;
607
      foreach ($variables['rows'] as $columns) {
merlinofchaos's avatar
merlinofchaos committed
608 609 610
        $empty &= empty($columns[$column]);
      }
      if ($empty) {
611
        foreach ($variables['rows'] as &$column_items) {
merlinofchaos's avatar
merlinofchaos committed
612
          unset($column_items[$column]);
613
          unset($variables['header'][$column]);
merlinofchaos's avatar
merlinofchaos committed
614 615 616 617 618 619
        }
      }
    }
  }

  // Hide table header if all labels are empty.
620
  if (!$has_header_labels) {
621
    $variables['header'] = array();
merlinofchaos's avatar
merlinofchaos committed
622 623
  }

624
  foreach ($variables['rows'] as $num => $row) {
625
    $variables['rows'][$num]['attributes'] = array();
626
    if ($row_class = $handler->getRowClass($num)) {
627
      $variables['rows'][$num]['attributes']['class'][] = $row_class;
merlinofchaos's avatar
merlinofchaos committed
628
    }
629
    $variables['rows'][$num]['attributes'] = new Attribute($variables['rows'][$num]['attributes']);
merlinofchaos's avatar
merlinofchaos committed
630 631
  }

632
  if (empty($variables['rows']) && !empty($options['empty_table'])) {
633
    $build = $view->display_handler->renderArea('empty');
634 635
    $variables['rows'][0]['columns'][0]['content'] = drupal_render($build);
    $variables['rows'][0]['attributes'] = new Attribute(array('class' => 'odd'));
merlinofchaos's avatar
merlinofchaos committed
636
    // Calculate the amounts of rows with output.
637
    $variables['rows'][0]['columns'][0]['attributes'] = new Attribute(array(
638
      'colspan' => count($variables['header']),
639 640
      'class' => 'views-empty',
    ));
merlinofchaos's avatar
merlinofchaos committed
641 642
  }

643
  $variables['sticky'] = FALSE;
merlinofchaos's avatar
merlinofchaos committed
644
  if (!empty($options['sticky'])) {
645
    $variables['view']->element['#attached']['library'][] = 'core/drupal.tableheader';
646
    $variables['sticky'] = TRUE;
merlinofchaos's avatar
merlinofchaos committed
647 648
  }

649 650
  // Add the caption to the list if set.
  if (!empty($handler->options['caption'])) {
651 652
    $variables['caption'] = Xss::filterAdmin($handler->options['caption']);
    $variables['caption_needed'] = TRUE;
merlinofchaos's avatar
merlinofchaos committed
653
  }
654
  else {
655 656
    $variables['caption'] = '';
    $variables['caption_needed'] = FALSE;
657 658
  }

659 660 661
  $variables['summary'] = $handler->options['summary'];
  $variables['description'] = $handler->options['description'];
  $variables['caption_needed'] |= !empty($variables['summary']) || !empty($variables['description']);
662

663
  $variables['responsive'] = FALSE;
664 665 666
  // 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.
667
  if (isset($variables['header']) && $responsive) {
668
    $variables['view']->element['#attached']['library'][] = 'core/drupal.tableresponsive';
669 670
    // Add 'responsive-enabled' class to the table to identify it for JS.
    // This is needed to target tables constructed by this function.
671
    $variables['responsive'] = TRUE;
672
  }
merlinofchaos's avatar
merlinofchaos committed
673 674 675
}

/**
676 677 678 679
 * Prepares variables for views grid style templates.
 *
 * Default template: views-view-grid.html.twig.
 *
680
 * @param array $variables
681 682 683
 *   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
684
 */
685
function template_preprocess_views_view_grid(&$variables) {
686 687 688 689 690 691 692 693 694 695
  $options = $variables['options'] = $variables['view']->style_plugin->options;
  $horizontal = ($options['alignment'] === 'horizontal');

  $col = 0;
  $row = 0;
  $items = array();
  $remainders = count($variables['rows']) % $options['columns'];
  $num_rows = floor(count($variables['rows']) / $options['columns']);

  // Iterate over each rendered views result row.
696
  foreach ($variables['rows'] as $result_index => $item) {
697 698 699 700 701 702 703 704

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

706 707 708 709
    // Create attributes for rows.
    if (!$horizontal || ($horizontal && empty($items[$row]['attributes']))) {
      $row_attributes = array('class' => array());
      // Add custom row classes.
710
      $row_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'row')));
711 712 713 714 715 716 717 718 719
      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
720 721
      }
    }
722 723 724 725 726 727

    // Create attributes for columns.
    if ($horizontal || (!$horizontal && empty($items[$col]['attributes']))) {
      $col_attributes = array('class' => array());
      // Add default views column classes.
      // Add custom column classes.
728
      $col_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'col')));
729 730 731 732 733 734 735 736 737 738 739 740 741 742
      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
743 744
    }

745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
    // 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
760 761 762 763 764 765 766 767 768 769 770 771
      if (!$remainders && $row == $num_rows) {
        $row = 0;
        $col++;
      }
      elseif ($remainders && $row == $num_rows + 1) {
        $row = 0;
        $col++;
        $remainders--;
      }
    }
  }

772 773
  // Add items to the variables array.
  $variables['items'] = $items;
merlinofchaos's avatar
merlinofchaos committed
774 775 776
}

/**
777 778 779 780
 * Prepares variables for views unformatted rows templates.
 *
 * Default template: views-view-unformatted.html.twig.
 *
781
 * @param array $variables
782 783 784
 *   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
785
 */
786 787 788
function template_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
merlinofchaos's avatar
merlinofchaos committed
789 790 791
  $style = $view->style_plugin;
  $options = $style->options;

792
  $variables['default_row_class'] = !empty($options['default_row_class']);
merlinofchaos's avatar
merlinofchaos committed
793
  foreach ($rows as $id => $row) {
794 795 796
    $variables['rows'][$id] = array();
    $variables['rows'][$id]['content'] = $row;
    $variables['rows'][$id]['attributes'] = array();
797
    $variables['rows'][$id]['attributes'] = new Attribute($variables['rows'][$id]['attributes']);
798
    if ($row_class = $view->style_plugin->getRowClass($id)) {
799
      $variables['rows'][$id]['attributes']->addClass($row_class);
merlinofchaos's avatar
merlinofchaos committed
800 801 802 803 804
    }
  }
}

/**
805 806 807 808 809 810 811
 * 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
812
 */
813 814
function template_preprocess_views_view_list(&$variables) {
  $handler  = $variables['view']->style_plugin;
merlinofchaos's avatar
merlinofchaos committed
815

816
  // Fetch classes from handler options.
817 818
  if ($handler->options['class']) {
    $class = explode(' ', $handler->options['class']);
819
    $class = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $class);
merlinofchaos's avatar
merlinofchaos committed
820

821 822 823
    // Initialize a new attribute class for $class.
    $variables['list']['attributes'] = new Attribute(array('class' => $class));
  }
merlinofchaos's avatar
merlinofchaos committed
824

825 826 827
  // Fetch wrapper classes from handler options.
  if ($handler->options['wrapper_class']) {
    $wrapper_class = explode(' ', $handler->options['wrapper_class']);
828
    $variables['attributes']['class'] = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $wrapper_class);
829 830
  }

831
  $variables['list']['type'] = $handler->options['type'];
832

833
  template_preprocess_views_view_unformatted($variables);
merlinofchaos's avatar
merlinofchaos committed
834 835 836
}

/**
837 838 839 840
 * Prepares variables for RSS feed templates.
 *
 * Default template: views-view-rss.html.twig.
 *
841
 * @param array $variables
842 843 844
 *   An associative array containing:
 *   - view: A ViewExecutable object.
 *   - rows: The raw row data.
845
 */
846
function template_preprocess_views_view_rss(&$variables) {
847
  $view  = $variables['view'];
848
  $items = $variables['rows'];
849
  $style = $view->style_plugin;
merlinofchaos's avatar
merlinofchaos committed
850

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

merlinofchaos's avatar
merlinofchaos committed
853 854 855
  // 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;).
856
  $variables['description'] = SafeMarkup::checkPlain(Html::decodeEntities(strip_tags($style->getDescription())));
merlinofchaos's avatar
merlinofchaos committed
857

858
  if ($view->display_handler->getOption('sitename_title')) {
859
    $title = $config->get('name');
860
    if ($slogan = $config->get('slogan')) {
merlinofchaos's avatar
merlinofchaos committed
861 862 863 864
      $title .= ' - ' . $slogan;
    }
  }
  else {
865
    $title = $view->getTitle();
merlinofchaos's avatar
merlinofchaos committed
866
  }
867
  $variables['title'] = SafeMarkup::checkPlain($title);
merlinofchaos's avatar
merlinofchaos committed
868

869 870
  // Figure out which display which has a path we're using for this feed. If
  // there isn't one, use the global $base_url
871
  $link_display_id = $view->display_handler->getLinkDisplay();
872
  if ($link_display_id && $display = $view->displayHandlers->get($link_display_id)) {
873
    $url = $view->getUrl(NULL, $link_display_id);
merlinofchaos's avatar
merlinofchaos committed
874 875
  }

876 877
  /** @var \Drupal\Core\Url $url */
  if ($url) {
merlinofchaos's avatar
merlinofchaos committed
878 879 880 881 882
    $url_options = array('absolute' => TRUE);
    if (!empty($view->exposed_raw_input)) {
      $url_options['query'] = $view->exposed_raw_input;
    }

883 884
    // Compare the link to the default home page; if it's the default home page,
    // just use $base_url.
885
    $url_string = $url->setOptions($url_options)->toString();
886 887 888
    // @todo Should page.front be stored with a leading slash? See
    //   https://www.drupal.org/node/2430595.
    if ($url_string === Url::fromUserInput('/' . $config->get('page.front'))->toString()) {
889
      $url_string = Url::fromRoute('<front>')->setAbsolute()->toString();
merlinofchaos's avatar
merlinofchaos committed
890 891
    }

892
    $variables['link'] = $url_string;
merlinofchaos's avatar
merlinofchaos committed
893 894
  }

895
  $variables['langcode'] = SafeMarkup::checkPlain(\Drupal::languageManager()->getCurrentLanguage()->getId());
896 897 898
  $variables['namespaces'] = new Attribute($style->namespaces);
  $variables['items'] = $items;
  $variables['channel_elements'] = format_xml_elements($style->channel_elements);
merlinofchaos's avatar
merlinofchaos committed
899 900 901

  // 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.
902 903
  if (empty($variables['view']->live_preview)) {
    $variables['view']->getResponse()->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
merlinofchaos's avatar
merlinofchaos committed
904 905 906 907
  }
}

/**
908 909 910 911
 * Prepares variables for views RSS item templates.
 *
 * Default template: views-view-row-rss.html.twig.
 *
912
 * @param array $variables
913 914
 *   An associative array containing:
 *   - row: The raw results rows.
merlinofchaos's avatar
merlinofchaos committed
915
 */
916 917
function template_preprocess_views_view_row_rss(&$variables) {
  $item = $variables['row'];
merlinofchaos's avatar
merlinofchaos committed
918

919
  $variables['title'] = SafeMarkup::checkPlain($item->title);
920
  $variables['link'] = $item->link;
921
  $variables['description'] = SafeMarkup::checkPlain($item->description);
922
  $variables['item_elements'] = empty($item->elements) ? '' : format_xml_elements($item->elements);
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'] = SafeMarkup::checkPlain($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
 */
1014
function template_preprocess_views_mini_pager(&$variables) {
merlinofchaos's avatar
merlinofchaos committed
1015 1016
  global $pager_page_array, $pager_total;

1017 1018 1019
  $tags = &$variables['tags'];
  $element = $variables['element'];
  $parameters = $variables['parameters'];
merlinofchaos's avatar
merlinofchaos committed
1020

1021
  // Current is the page we are currently paged to.
1022
  $variables['items']['current'] = $pager_page_array[$element] + 1;
merlinofchaos's avatar
merlinofchaos committed
1023

1024
  if ($pager_total[$element] > 1 && $pager_page_array[$element] > 0) {
1025 1026
    $options = array(
      'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
merlinofchaos's avatar
merlinofchaos committed
1027
    );
1028 1029 1030 1031 1032
    $variables['items']['previous']['href'] = \Drupal::url('<current>', [], $options);
    if (isset($tags[1])) {
      $variables['items']['previous']['text'] = $tags[1];
    }
    $variables['items']['previous']['attributes'] = new Attribute();
1033
  }
merlinofchaos's avatar
merlinofchaos committed
1034