39e741420ae5ad5be48097ddc4b88fe4b69de52e
[yaffs-website] / web / core / modules / views / views.theme.inc
1 <?php
2
3 /**
4  * @file
5  * Preprocessors and helper functions to make theming easier.
6  */
7
8 use Drupal\Component\Utility\Html;
9 use Drupal\Component\Utility\Xss;
10 use Drupal\Core\Template\Attribute;
11 use Drupal\Core\Url;
12
13 /**
14  * Prepares variables for view templates.
15  *
16  * Default template: views-view.html.twig.
17  *
18  * @param array $variables
19  *   An associative array containing:
20  *   - view: The ViewExecutable object.
21  */
22 function template_preprocess_views_view(&$variables) {
23   $view = $variables['view'];
24   $id = $view->storage->id();
25
26   $variables['css_name'] = Html::cleanCssIdentifier($id);
27   $variables['id'] = $id;
28   $variables['display_id'] = $view->current_display;
29   // Override the title to be empty by default. For example, if viewing a page
30   // view, 'title' will already be populated in $variables. This can still be
31   // overridden to use a title when needed. See views_ui_preprocess_views_view()
32   // for an example of this.
33   $variables['title'] = '';
34
35   $css_class = $view->display_handler->getOption('css_class');
36   if (!empty($css_class)) {
37     $variables['css_class'] = preg_replace('/[^a-zA-Z0-9- ]/', '-', $css_class);
38     $variables['attributes']['class'][] = $variables['css_class'];
39   }
40
41   // contextual_preprocess() only works on render elements, and since this theme
42   // hook is not for a render element, contextual_preprocess() falls back to the
43   // first argument and checks if that is a render element. The first element is
44   // view_array. However, view_array does not get set anywhere, but since we do
45   // have access to the View object, we can also access the View object's
46   // element, which is a render element that does have #contextual_links set if
47   // the display supports it. Doing this allows contextual_preprocess() to
48   // access this theme hook's render element, and therefore allows this template
49   // to have contextual links.
50   // @see views_theme()
51   $variables['view_array'] = $variables['view']->element;
52
53   // Attachments are always updated with the outer view, never by themselves,
54   // so they do not have dom ids.
55   if (empty($view->is_attachment)) {
56     // Our JavaScript needs to have some means to find the HTML belonging to
57     // this view.
58     //
59     // It is true that the DIV wrapper has classes denoting the name of the view
60     // and its display ID, but this is not enough to unequivocally match a view
61     // with its HTML, because one view may appear several times on the page. So
62     // we set up a hash with the current time, $dom_id, to issue a "unique"
63     // identifier for each view. This identifier is written to both
64     // drupalSettings and the DIV wrapper.
65     $variables['dom_id'] = $view->dom_id;
66   }
67 }
68
69 /**
70  * Prepares variables for views fields templates.
71  *
72  * Default template: views-view-fields.html.twig.
73  *
74  * @param array $variables
75  *   An associative array containing:
76  *   - view: The view object.
77  *   - options: An array of options. Each option contains:
78  *     - inline: An array that contains the fields that are to be
79  *       displayed inline.
80  *     - default_field_elements: If default field wrapper
81  *       elements are to be provided.
82  *     - hide_empty: Whether the field is to be hidden if empty.
83  *     - element_default_classes: If the default classes are to be added.
84  *     - separator: A string to be placed between inline fields to keep them
85  *       visually distinct.
86  *    - row: An array containing information about the current row.
87  */
88 function template_preprocess_views_view_fields(&$variables) {
89   $view = $variables['view'];
90
91   // Loop through the fields for this view.
92   $previous_inline = FALSE;
93   $variables['fields'] = []; // ensure it's at least an empty array.
94   /** @var \Drupal\views\ResultRow $row */
95   $row = $variables['row'];
96   foreach ($view->field as $id => $field) {
97     // 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'])))) {
101       $object = new stdClass();
102       $object->handler = $view->field[$id];
103       $object->inline = !empty($variables['options']['inline'][$id]);
104       // Set up default value of the flag that indicates whether to display a
105       // colon after the label.
106       $object->has_label_colon = FALSE;
107
108       $object->element_type = $object->handler->elementType(TRUE, !$variables['options']['default_field_elements'], $object->inline);
109       if ($object->element_type) {
110         $attributes = [];
111         if ($object->handler->options['element_default_classes']) {
112           $attributes['class'][] = 'field-content';
113         }
114
115         if ($classes = $object->handler->elementClasses($row->index)) {
116           $attributes['class'][] = $classes;
117         }
118         $object->element_attributes = new Attribute($attributes);
119       }
120
121       $object->content = $field_output;
122       if (isset($view->field[$id]->field_alias) && isset($row->{$view->field[$id]->field_alias})) {
123         $object->raw = $row->{$view->field[$id]->field_alias};
124       }
125       else {
126         $object->raw = NULL; // make sure it exists to reduce NOTICE
127       }
128
129       if (!empty($variables['options']['separator']) && $previous_inline && $object->inline && $object->content) {
130         $object->separator = Xss::filterAdmin($variables['options']['separator']);
131       }
132
133       $object->class = Html::cleanCssIdentifier($id);
134
135       $previous_inline = $object->inline;
136       // Set up field wrapper element.
137       $object->wrapper_element = $object->handler->elementWrapperType(TRUE, TRUE);
138       if ($object->wrapper_element === '' && $variables['options']['default_field_elements']) {
139         $object->wrapper_element = $object->inline ? 'span' : 'div';
140       }
141
142       // Set up field wrapper attributes if field wrapper was set.
143       if ($object->wrapper_element) {
144         $attributes = [];
145         if ($object->handler->options['element_default_classes']) {
146           $attributes['class'][] = 'views-field';
147           $attributes['class'][] = 'views-field-' . $object->class;
148         }
149
150         if ($classes = $object->handler->elementWrapperClasses($row->index)) {
151           $attributes['class'][] = $classes;
152         }
153         $object->wrapper_attributes = new Attribute($attributes);
154       }
155
156       // Set up field label
157       $object->label = $view->field[$id]->label();
158
159       // Set up field label wrapper and its attributes.
160       if ($object->label) {
161         // Add a colon in a label suffix.
162         if ($object->handler->options['element_label_colon']) {
163           $object->label_suffix = ': ';
164           $object->has_label_colon = TRUE;
165         }
166
167         // Set up label HTML element.
168         $object->label_element = $object->handler->elementLabelType(TRUE, !$variables['options']['default_field_elements']);
169
170         // Set up label attributes.
171         if ($object->label_element) {
172           $attributes = [];
173           if ($object->handler->options['element_default_classes']) {
174             $attributes['class'][] = 'views-label';
175             $attributes['class'][] = 'views-label-' . $object->class;
176           }
177
178           // Set up field label.
179           $element_label_class = $object->handler->elementLabelClasses($row->index);
180           if ($element_label_class) {
181             $attributes['class'][] = $element_label_class;
182           }
183           $object->label_attributes = new Attribute($attributes);
184         }
185       }
186
187       $variables['fields'][$id] = $object;
188     }
189   }
190
191 }
192
193 /**
194  * Prepares variables for views single grouping templates.
195  *
196  * Default template: views-view-grouping.html.twig.
197  *
198  * @param array $variables
199  *   An associative array containing:
200  *   - view: The view object.
201  *   - rows: The rows returned from the view.
202  *   - grouping_level: Integer indicating the hierarchical level of the
203  *     grouping.
204  *   - content: The content to be grouped.
205  *   - title: The group heading.
206  */
207 function template_preprocess_views_view_grouping(&$variables) {
208   $variables['content'] = $variables['view']->style_plugin->renderGroupingSets($variables['rows'], $variables['grouping_level']);
209 }
210
211 /**
212  * Prepares variables for views field templates.
213  *
214  * Default template: views-view-field.html.twig.
215  *
216  * @param array $variables
217  *   An associative array containing:
218  *   - field: The field handler object for the current field.
219  *   - row: Object representing the raw result of the SQL query for the current
220  *     field.
221  *   - view: Instance of the ViewExecutable object for the parent view.
222  */
223 function template_preprocess_views_view_field(&$variables) {
224   $variables['output'] = $variables['field']->advancedRender($variables['row']);
225 }
226
227 /**
228  * Prepares variables for views summary templates.
229  *
230  * The summary prints a single record from a row, with fields.
231  *
232  * Default template: views-view-summary.html.twig.
233  *
234  * @param array $variables
235  *   An associative array containing:
236  *   - view: A ViewExecutable object.
237  *   - rows: The raw row data.
238  */
239 function template_preprocess_views_view_summary(&$variables) {
240   /** @var \Drupal\views\ViewExecutable $view */
241   $view = $variables['view'];
242   $argument = $view->argument[$view->build_info['summary_level']];
243
244   $url_options = [];
245
246   if (!empty($view->exposed_raw_input)) {
247     $url_options['query'] = $view->exposed_raw_input;
248   }
249
250   $active_urls = [
251     // Force system path.
252     \Drupal::url('<current>', [], ['alias' => TRUE]),
253     // Force system path.
254     Url::fromRouteMatch(\Drupal::routeMatch())->setOption('alias', TRUE)->toString(),
255     // Could be an alias.
256     \Drupal::url('<current>'),
257     // Could be an alias.
258     Url::fromRouteMatch(\Drupal::routeMatch())->toString(),
259   ];
260   $active_urls = array_combine($active_urls, $active_urls);
261
262   // Collect all arguments foreach row, to be able to alter them for example
263   // by the validator. This is not done per single argument value, because this
264   // could cause performance problems.
265   $row_args = [];
266
267   foreach ($variables['rows'] as $id => $row) {
268     $row_args[$id] = $argument->summaryArgument($row);
269   }
270   $argument->processSummaryArguments($row_args);
271
272   foreach ($variables['rows'] as $id => $row) {
273     $variables['rows'][$id]->attributes = [];
274     $variables['rows'][$id]->link = $argument->summaryName($row);
275     $args = $view->args;
276     $args[$argument->position] = $row_args[$id];
277
278     if (!empty($argument->options['summary_options']['base_path'])) {
279       $base_path = $argument->options['summary_options']['base_path'];
280       $tokens = $view->getDisplay()->getArgumentsTokens();
281       $base_path = $argument->globalTokenReplace($base_path, $tokens);
282       // @todo Views should expect and store a leading /. See:
283       //   https://www.drupal.org/node/2423913
284       $url = Url::fromUserInput('/' . $base_path);
285       try {
286         /** @var \Symfony\Component\Routing\Route $route */
287         $route_name = $url->getRouteName();
288         $route = \Drupal::service('router.route_provider')->getRouteByName($route_name);
289
290         $route_variables = $route->compile()->getVariables();
291         $parameters = $url->getRouteParameters();
292
293         foreach ($route_variables as $variable_name) {
294           $parameters[$variable_name] = array_shift($args);
295         }
296
297         $url->setRouteParameters($parameters);
298       }
299       catch (Exception $e) {
300         // If the given route doesn't exist, default to <front>
301         $url = Url::fromRoute('<front>');
302       }
303     }
304     else {
305       $url = $view->getUrl($args)->setOptions($url_options);
306     }
307     $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]);
311   }
312 }
313
314 /**
315  * Prepares variables for unformatted summary view templates.
316  *
317  * Default template: views-view-summary-unformatted.html.twig.
318  *
319  * @param array $variables
320  *   An associative array containing:
321  *   - view: A ViewExecutable object.
322  *   - rows: The raw row data.
323  *   - options: An array of options. Each option contains:
324  *     - separator: A string to be placed between inline fields to keep them
325  *       visually distinct.
326  */
327 function template_preprocess_views_view_summary_unformatted(&$variables) {
328   /** @var \Drupal\views\ViewExecutable $view */
329   $view = $variables['view'];
330   $argument = $view->argument[$view->build_info['summary_level']];
331
332   $url_options = [];
333
334   if (!empty($view->exposed_raw_input)) {
335     $url_options['query'] = $view->exposed_raw_input;
336   }
337
338   $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);
346
347   // Collect all arguments for each row, to be able to alter them for example
348   // by the validator. This is not done per single argument value, because
349   // this could cause performance problems.
350   $row_args = [];
351   foreach ($variables['rows'] as $id => $row) {
352     $row_args[$id] = $argument->summaryArgument($row);
353   }
354   $argument->processSummaryArguments($row_args);
355
356   foreach ($variables['rows'] as $id => $row) {
357     // Only false on first time.
358     if ($count++) {
359       $variables['rows'][$id]->separator = Xss::filterAdmin($variables['options']['separator']);
360     }
361     $variables['rows'][$id]->attributes = [];
362     $variables['rows'][$id]->link = $argument->summaryName($row);
363     $args = $view->args;
364     $args[$argument->position] = $row_args[$id];
365
366     if (!empty($argument->options['summary_options']['base_path'])) {
367       $base_path = $argument->options['summary_options']['base_path'];
368       $tokens = $view->getDisplay()->getArgumentsTokens();
369       $base_path = $argument->globalTokenReplace($base_path, $tokens);
370       // @todo Views should expect and store a leading /. See:
371       //   https://www.drupal.org/node/2423913
372       $url = Url::fromUserInput('/' . $base_path);
373       try {
374         /** @var \Symfony\Component\Routing\Route $route */
375         $route = \Drupal::service('router.route_provider')->getRouteByName($url->getRouteName());
376         $route_variables = $route->compile()->getVariables();
377         $parameters = $url->getRouteParameters();
378
379         foreach ($route_variables as $variable_name) {
380           $parameters[$variable_name] = array_shift($args);
381         }
382
383         $url->setRouteParameters($parameters);
384       }
385       catch (Exception $e) {
386         // If the given route doesn't exist, default to <front>
387         $url = Url::fromRoute('<front>');
388       }
389     }
390     else {
391       $url = $view->getUrl($args)->setOptions($url_options);
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);
397   }
398 }
399
400 /**
401  * Prepares variables for views table templates.
402  *
403  * Default template: views-view-table.html.twig.
404  *
405  * @param array $variables
406  *   An associative array containing:
407  *   - view: A ViewExecutable object.
408  *   - rows: The raw row data.
409  */
410 function template_preprocess_views_view_table(&$variables) {
411   $view = $variables['view'];
412
413   // We need the raw data for this grouping, which is passed in
414   // as $variables['rows'].
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']
417   // so that it can get rebuilt.
418   // Store rows so that they may be used by further preprocess functions.
419   $result = $variables['result'] = $variables['rows'];
420   $variables['rows'] = [];
421   $variables['header'] = [];
422
423   $options = $view->style_plugin->options;
424   $handler = $view->style_plugin;
425
426   $fields = &$view->field;
427   $columns = $handler->sanitizeColumns($options['columns'], $fields);
428
429   $active = !empty($handler->active) ? $handler->active : '';
430   $order = !empty($handler->order) ? $handler->order : 'asc';
431
432   // A boolean variable which stores whether the table has a responsive class.
433   $responsive = FALSE;
434
435   // For the actual site we want to not render full URLs, because this would
436   // make pagers cacheable per URL, which is problematic in blocks, for example.
437   // For the actual live preview though the javascript relies on properly
438   // working URLs.
439   $route_name = !empty($view->live_preview) ? '<current>' : '<none>';
440
441   $query = tablesort_get_query_parameters();
442   if (isset($view->exposed_raw_input)) {
443     $query += $view->exposed_raw_input;
444   }
445
446   // A boolean to store whether the table's header has any labels.
447   $has_header_labels = FALSE;
448   foreach ($columns as $field => $column) {
449     // Create a second variable so we can easily find what fields we have and
450     // what the CSS classes should be.
451     $variables['fields'][$field] = Html::cleanCssIdentifier($field);
452     if ($active == $field) {
453       $variables['fields'][$field] .= ' is-active';
454     }
455
456     // Render the header labels.
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;
461       }
462       else {
463         $initial = !empty($options['info'][$field]['default_sort_order']) ? $options['info'][$field]['default_sort_order'] : 'asc';
464
465         if ($active == $field) {
466           $initial = ($order == 'asc') ? 'desc' : 'asc';
467         }
468
469         $title = t('sort by @s', ['@s' => $label]);
470         if ($active == $field) {
471           $variables['header'][$field]['sort_indicator'] = [
472             '#theme' => 'tablesort_indicator',
473             '#style' => $initial,
474           ];
475         }
476
477         $query['order'] = $field;
478         $query['sort'] = $initial;
479         $link_options = [
480           'query' => $query,
481         ];
482         $url = new Url($route_name, [], $link_options);
483         $variables['header'][$field]['url'] = $url->toString();
484         $variables['header'][$field]['content'] = $label;
485         $variables['header'][$field]['title'] = $title;
486       }
487
488       $variables['header'][$field]['default_classes'] = $fields[$field]->options['element_default_classes'];
489       // Set up the header label class.
490       $variables['header'][$field]['attributes'] = [];
491       $class = $fields[$field]->elementLabelClasses(0);
492       if ($class) {
493         $variables['header'][$field]['attributes']['class'][] = $class;
494       }
495       // Add responsive header classes.
496       if (!empty($options['info'][$field]['responsive'])) {
497         $variables['header'][$field]['attributes']['class'][] = $options['info'][$field]['responsive'];
498         $responsive = TRUE;
499       }
500       // Add a CSS align class to each field if one was set.
501       if (!empty($options['info'][$field]['align'])) {
502         $variables['header'][$field]['attributes']['class'][] = Html::cleanCssIdentifier($options['info'][$field]['align']);
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);
507         if ($element_label_type) {
508           $variables['header'][$field]['wrapper_element'] = $element_label_type;
509         }
510         // Improves accessibility of complex tables.
511         $variables['header'][$field]['attributes']['id'] = Html::getUniqueId('view-' . $field . '-table-column');
512       }
513       // Check if header label is not empty.
514       if (!empty($variables['header'][$field]['content'])) {
515         $has_header_labels = TRUE;
516       }
517
518       $variables['header'][$field]['attributes'] = new Attribute($variables['header'][$field]['attributes']);
519     }
520
521     // Add a CSS align class to each field if one was set.
522     if (!empty($options['info'][$field]['align'])) {
523       $variables['fields'][$field] .= ' ' . Html::cleanCssIdentifier($options['info'][$field]['align']);
524     }
525
526     // Render each field into its appropriate column.
527     foreach ($result as $num => $row) {
528
529       // Skip building the attributes and content if the field is to be excluded
530       // from the display.
531       if (!empty($fields[$field]->options['exclude'])) {
532         continue;
533       }
534
535       // Reference to the column in the loop to make the code easier to read.
536       $column_reference =& $variables['rows'][$num]['columns'][$column];
537
538       $column_reference['default_classes'] = $fields[$field]->options['element_default_classes'];
539
540       // Set the field key to the column so it can be used for adding classes
541       // in a template.
542       $column_reference['fields'][] = $variables['fields'][$field];
543
544       // Add field classes.
545       if (!isset($column_reference['attributes'])) {
546         $column_reference['attributes'] = [];
547       }
548
549       if ($classes = $fields[$field]->elementClasses($num)) {
550         $column_reference['attributes']['class'][] = $classes;
551       }
552
553       // Add responsive header classes.
554       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         $column_reference['wrapper_element'] = $fields[$field]->elementType(TRUE, TRUE);
566         if (!isset($column_reference['content'])) {
567           $column_reference['content'] = [];
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           if (!empty($column_reference['content']) && !empty($options['info'][$column]['separator'])) {
574             $column_reference['content'][] = [
575               'separator' => ['#markup' => $options['info'][$column]['separator']],
576               'field_output' => ['#markup' => $field_output]
577             ];
578           }
579           else {
580             $column_reference['content'][] = [
581               'field_output' => ['#markup' => $field_output]
582             ];
583           }
584         }
585       }
586       $column_reference['attributes'] = new Attribute($column_reference['attributes']);
587     }
588
589     // Remove columns if the "empty_column" option is checked and the
590     // field is empty.
591     if (!empty($options['info'][$field]['empty_column'])) {
592       $empty = TRUE;
593       foreach ($variables['rows'] as $columns) {
594         $empty &= empty($columns['columns'][$column]['content']);
595       }
596       if ($empty) {
597         foreach ($variables['rows'] as &$column_items) {
598           unset($column_items['columns'][$column]);
599         }
600         unset($variables['header'][$column]);
601       }
602     }
603   }
604
605   // Hide table header if all labels are empty.
606   if (!$has_header_labels) {
607     $variables['header'] = [];
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;
614     }
615     $variables['rows'][$num]['attributes'] = new Attribute($variables['rows'][$num]['attributes']);
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']]);
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     ]);
627   }
628
629   $variables['sticky'] = FALSE;
630   if (!empty($options['sticky'])) {
631     $variables['view']->element['#attached']['library'][] = 'core/drupal.tableheader';
632     $variables['sticky'] = TRUE;
633   }
634
635   // Add the caption to the list if set.
636   if (!empty($handler->options['caption'])) {
637     $variables['caption'] = ['#markup' => $handler->options['caption']];
638     $variables['caption_needed'] = TRUE;
639   }
640   elseif (!empty($variables['title'])) {
641     $variables['caption'] = ['#markup' => $variables['title']];
642     $variables['caption_needed'] = TRUE;
643   }
644   else {
645     $variables['caption'] = '';
646     $variables['caption_needed'] = FALSE;
647   }
648
649   $variables['summary'] = $handler->options['summary'];
650   $variables['description'] = $handler->options['description'];
651   $variables['caption_needed'] |= !empty($variables['summary']) || !empty($variables['description']);
652
653   $variables['responsive'] = FALSE;
654   // If the table has headers and it should react responsively to columns hidden
655   // with the classes represented by the constants RESPONSIVE_PRIORITY_MEDIUM
656   // and RESPONSIVE_PRIORITY_LOW, add the tableresponsive behaviors.
657   if (isset($variables['header']) && $responsive) {
658     $variables['view']->element['#attached']['library'][] = 'core/drupal.tableresponsive';
659     // Add 'responsive-enabled' class to the table to identify it for JS.
660     // This is needed to target tables constructed by this function.
661     $variables['responsive'] = TRUE;
662   }
663 }
664
665 /**
666  * Prepares variables for views grid style templates.
667  *
668  * Default template: views-view-grid.html.twig.
669  *
670  * @param array $variables
671  *   An associative array containing:
672  *   - view: The view object.
673  *   - rows: An array of row items. Each row is an array of content.
674  */
675 function template_preprocess_views_view_grid(&$variables) {
676   $options = $variables['options'] = $variables['view']->style_plugin->options;
677   $horizontal = ($options['alignment'] === 'horizontal');
678
679   $col = 0;
680   $row = 0;
681   $items = [];
682   $remainders = count($variables['rows']) % $options['columns'];
683   $num_rows = floor(count($variables['rows']) / $options['columns']);
684
685   // Iterate over each rendered views result row.
686   foreach ($variables['rows'] as $result_index => $item) {
687
688     // Add the item.
689     if ($horizontal) {
690       $items[$row]['content'][$col]['content'] = $item;
691     }
692     else {
693       $items[$col]['content'][$row]['content'] = $item;
694     }
695
696     // Create attributes for rows.
697     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       if (!empty($row_class)) {
702         $row_attributes['class'] = array_merge($row_attributes['class'], $row_class);
703       }
704       // Add row attributes to the item.
705       if ($horizontal) {
706         $items[$row]['attributes'] = new Attribute($row_attributes);
707       }
708       else {
709         $items[$col]['content'][$row]['attributes'] = new Attribute($row_attributes);
710       }
711     }
712
713     // Create attributes for columns.
714     if ($horizontal || (!$horizontal && empty($items[$col]['attributes']))) {
715       $col_attributes = ['class' => []];
716       // Add default views column classes.
717       // Add custom column classes.
718       $col_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'col')));
719       if (!empty($col_class)) {
720         $col_attributes['class'] = array_merge($col_attributes['class'], $col_class);
721       }
722       // Add automatic width for columns.
723       if ($options['automatic_width']) {
724         $col_attributes['style'] = 'width: ' . (100 / $options['columns']) . '%;';
725       }
726       // Add column attributes to the item.
727       if ($horizontal) {
728         $items[$row]['content'][$col]['attributes'] = new Attribute($col_attributes);
729       }
730       else {
731         $items[$col]['attributes'] = new Attribute($col_attributes);
732       }
733     }
734
735     // Increase, decrease or reset appropriate integers.
736     if ($horizontal) {
737       if ($col == 0 && $col != ($options['columns'] - 1)) {
738         $col++;
739       }
740       elseif ($col >= ($options['columns'] - 1)) {
741         $col = 0;
742         $row++;
743       }
744       else {
745         $col++;
746       }
747     }
748     else {
749       $row++;
750       if (!$remainders && $row == $num_rows) {
751         $row = 0;
752         $col++;
753       }
754       elseif ($remainders && $row == $num_rows + 1) {
755         $row = 0;
756         $col++;
757         $remainders--;
758       }
759     }
760   }
761
762   // Add items to the variables array.
763   $variables['items'] = $items;
764 }
765
766 /**
767  * Prepares variables for views unformatted rows templates.
768  *
769  * Default template: views-view-unformatted.html.twig.
770  *
771  * @param array $variables
772  *   An associative array containing:
773  *   - view: The view object.
774  *   - rows: An array of row items. Each row is an array of content.
775  */
776 function template_preprocess_views_view_unformatted(&$variables) {
777   $view = $variables['view'];
778   $rows = $variables['rows'];
779   $style = $view->style_plugin;
780   $options = $style->options;
781
782   $variables['default_row_class'] = !empty($options['default_row_class']);
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);
789     }
790   }
791 }
792
793 /**
794  * Prepares variables for Views HTML list templates.
795  *
796  * Default template: views-view-list.html.twig.
797  *
798  * @param array $variables
799  *   An associative array containing:
800  *   - view: A View object.
801  */
802 function template_preprocess_views_view_list(&$variables) {
803   $handler  = $variables['view']->style_plugin;
804
805   // Fetch classes from handler options.
806   if ($handler->options['class']) {
807     $class = explode(' ', $handler->options['class']);
808     $class = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $class);
809
810     // Initialize a new attribute class for $class.
811     $variables['list']['attributes'] = new Attribute(['class' => $class]);
812   }
813
814   // Fetch wrapper classes from handler options.
815   if ($handler->options['wrapper_class']) {
816     $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);
823 }
824
825 /**
826  * Prepares variables for RSS feed templates.
827  *
828  * Default template: views-view-rss.html.twig.
829  *
830  * @param array $variables
831  *   An associative array containing:
832  *   - view: A ViewExecutable object.
833  *   - 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;
839
840   $config = \Drupal::config('system.site');
841
842   // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
843   // We strip all HTML tags, but need to prevent double encoding from properly
844   // escaped source data (such as &amp becoming &amp;amp;).
845   $variables['description'] = Html::decodeEntities(strip_tags($style->getDescription()));
846
847   if ($view->display_handler->getOption('sitename_title')) {
848     $title = $config->get('name');
849     if ($slogan = $config->get('slogan')) {
850       $title .= ' - ' . $slogan;
851     }
852   }
853   else {
854     $title = $view->getTitle();
855   }
856   $variables['title'] = $title;
857
858   // Figure out which display which has a path we're using for this feed. If
859   // there isn't one, use the global $base_url
860   $link_display_id = $view->display_handler->getLinkDisplay();
861   /** @var \Drupal\views\Plugin\views\display\DisplayPluginBase $display */
862   if ($link_display_id && ($display = $view->displayHandlers->get($link_display_id)) && $display->isEnabled()) {
863     $url = $view->getUrl(NULL, $link_display_id);
864   }
865
866   /** @var \Drupal\Core\Url $url */
867   if (!empty($url)) {
868     $url_options = ['absolute' => TRUE];
869     if (!empty($view->exposed_raw_input)) {
870       $url_options['query'] = $view->exposed_raw_input;
871     }
872
873     // Compare the link to the default home page; if it's the default home page,
874     // just use $base_url.
875     $url_string = $url->setOptions($url_options)->toString();
876     if ($url_string === Url::fromUserInput($config->get('page.front'))->toString()) {
877       $url_string = Url::fromRoute('<front>')->setAbsolute()->toString();
878     }
879
880     $variables['link'] = $url_string;
881   }
882
883   $variables['langcode'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
884   $variables['namespaces'] = new Attribute($style->namespaces);
885   $variables['items'] = $items;
886   $variables['channel_elements'] = \Drupal::service('renderer')->render($style->channel_elements);
887
888   // During live preview we don't want to output the header since the contents
889   // of the feed are being displayed inside a normal HTML page.
890   if (empty($variables['view']->live_preview)) {
891     $variables['view']->getResponse()->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
892   }
893 }
894
895 /**
896  * Prepares variables for views RSS item templates.
897  *
898  * Default template: views-view-row-rss.html.twig.
899  *
900  * @param array $variables
901  *   An associative array containing:
902  *   - row: The raw results rows.
903  */
904 function template_preprocess_views_view_row_rss(&$variables) {
905   $item = $variables['row'];
906   $variables['title'] = $item->title;
907   $variables['link'] = $item->link;
908
909   // The description is the only place where we should find HTML.
910   // @see https://validator.w3.org/feed/docs/rss2.html#hrelementsOfLtitemgt
911   // If we have a render array, render it here and pass the result to the
912   // template, letting Twig autoescape it.
913   if (isset($item->description) && is_array($item->description)) {
914     $variables['description'] = (string) \Drupal::service('renderer')->render($item->description);
915   }
916
917   $variables['item_elements'] = [];
918   foreach ($item->elements as $element) {
919     if (isset($element['attributes']) && is_array($element['attributes'])) {
920       $element['attributes'] = new Attribute($element['attributes']);
921     }
922     $variables['item_elements'][] = $element;
923   }
924 }
925
926 /**
927  * Prepares variables for OPML feed templates.
928  *
929  * Default template: views-view-opml.html.twig.
930  *
931  * @param array $variables
932  *   An associative array containing:
933  *   - view: A ViewExecutable object.
934  *   - rows: The raw row data.
935  */
936 function template_preprocess_views_view_opml(&$variables) {
937   $view  = $variables['view'];
938   $items = $variables['rows'];
939
940   $config = \Drupal::config('system.site');
941
942   if ($view->display_handler->getOption('sitename_title')) {
943     $title = $config->get('name');
944     if ($slogan = $config->get('slogan')) {
945       $title .= ' - ' . $slogan;
946     }
947   }
948   else {
949     $title = $view->getTitle();
950   }
951   $variables['title'] = $title;
952   $variables['items'] = $items;
953   $variables['updated'] = gmdate(DATE_RFC2822, REQUEST_TIME);
954
955   // During live preview we don't want to output the header since the contents
956   // of the feed are being displayed inside a normal HTML page.
957   if (empty($variables['view']->live_preview)) {
958     $variables['view']->getResponse()->headers->set('Content-Type', 'text/xml; charset=utf-8');
959   }
960 }
961
962 /**
963  * Prepares variables for views OPML item templates.
964  *
965  * Default template: views-view-row-opml.html.twig.
966  *
967  * @param array $variables
968  *   An associative array containing:
969  *   - row: The raw results rows.
970  */
971 function template_preprocess_views_view_row_opml(&$variables) {
972   $item = $variables['row'];
973
974   $variables['attributes'] = new Attribute($item);
975 }
976
977 /**
978  * Prepares variables for views exposed form templates.
979  *
980  * Default template: views-exposed-form.html.twig.
981  *
982  * @param array $variables
983  *   An associative array containing:
984  *   - form: A render element representing the form.
985  */
986 function template_preprocess_views_exposed_form(&$variables) {
987   $form = &$variables['form'];
988
989   if (!empty($form['q'])) {
990     $variables['q'] = $form['q'];
991   }
992
993   foreach ($form['#info'] as $info) {
994     if (!empty($info['label'])) {
995       $form[$info['value']]['#title'] = $info['label'];
996     }
997     if (!empty($info['description'])) {
998       $form[$info['value']]['#description'] = $info['description'];
999     }
1000   }
1001 }
1002
1003 /**
1004  * Prepares variables for views mini-pager templates.
1005  *
1006  * Default template: views-mini-pager.html.twig.
1007  *
1008  * @param array $variables
1009  *   An associative array containing:
1010  *   - tags: Provides link text for the next/previous links.
1011  *   - element: The pager's id.
1012  *   - parameters: Any extra GET parameters that should be retained, such as
1013  *     exposed input.
1014  */
1015 function template_preprocess_views_mini_pager(&$variables) {
1016   global $pager_page_array, $pager_total;
1017
1018   $tags = &$variables['tags'];
1019   $element = $variables['element'];
1020   $parameters = $variables['parameters'];
1021
1022   // Current is the page we are currently paged to.
1023   $variables['items']['current'] = $pager_page_array[$element] + 1;
1024
1025   if ($pager_total[$element] > 1 && $pager_page_array[$element] > 0) {
1026     $options = [
1027       'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
1028     ];
1029     $variables['items']['previous']['href'] = \Drupal::url('<current>', [], $options);
1030     if (isset($tags[1])) {
1031       $variables['items']['previous']['text'] = $tags[1];
1032     }
1033     $variables['items']['previous']['attributes'] = new Attribute();
1034   }
1035
1036   if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
1037     $options = [
1038       'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
1039     ];
1040     $variables['items']['next']['href'] = \Drupal::url('<current>', [], $options);
1041     if (isset($tags[3])) {
1042       $variables['items']['next']['text'] = $tags[3];
1043     }
1044     $variables['items']['next']['attributes'] = new Attribute();
1045   }
1046
1047   // This is based on the entire current query string. We need to ensure
1048   // cacheability is affected accordingly.
1049   $variables['#cache']['contexts'][] = 'url.query_args';
1050 }
1051
1052 /**
1053  * @defgroup views_templates Views template files
1054  * @{
1055  * Describes various views templates & overriding options.
1056  *
1057  * All views templates can be overridden with a variety of names, using
1058  * the view, the display ID of the view, the display type of the view,
1059  * or some combination thereof.
1060  *
1061  * For each view, there will be a minimum of two templates used. The first
1062  * is used for all views: views-view.html.twig.
1063  *
1064  * The second template is determined by the style selected for the view. Note
1065  * that certain aspects of the view can also change which style is used; for
1066  * example, arguments which provide a summary view might change the style to
1067  * one of the special summary styles.
1068  *
1069  * The default style for all views is views-view-unformatted.html.twig.
1070  *
1071  * Many styles will then farm out the actual display of each row to a row
1072  * style; the default row style is views-view-fields.html.twig.
1073  *
1074  * Here is an example of all the templates that will be tried in the following
1075  * case:
1076  *
1077  * View, named foobar. Style: unformatted. Row style: Fields. Display: Page.
1078  *
1079  * - views-view--foobar--page.html.twig
1080  * - views-view--page.html.twig
1081  * - views-view--foobar.html.twig
1082  * - views-view.html.twig
1083  *
1084  * - views-view-unformatted--foobar--page.html.twig
1085  * - views-view-unformatted--page.html.twig
1086  * - views-view-unformatted--foobar.html.twig
1087  * - views-view-unformatted.html.twig
1088  *
1089  * - views-view-fields--foobar--page.html.twig
1090  * - views-view-fields--page.html.twig
1091  * - views-view-fields--foobar.html.twig
1092  * - views-view-fields.html.twig
1093  *
1094  * Important! When adding a new template to your theme, be sure to flush the
1095  * theme registry cache!
1096  *
1097  * @ingroup views_overview
1098  * @see \Drupal\views\ViewExecutable::buildThemeFunctions()
1099  * @}
1100  */