5 * Preprocessors and helper functions to make theming easier.
8 use Drupal\Component\Utility\Html;
9 use Drupal\Component\Utility\Xss;
10 use Drupal\Core\Template\Attribute;
14 * Prepares variables for view templates.
16 * Default template: views-view.html.twig.
18 * @param array $variables
19 * An associative array containing:
20 * - view: The ViewExecutable object.
22 function template_preprocess_views_view(&$variables) {
23 $view = $variables['view'];
24 $id = $view->storage->id();
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'] = '';
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'];
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.
51 $variables['view_array'] = $variables['view']->element;
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
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;
70 * Prepares variables for views fields templates.
72 * Default template: views-view-fields.html.twig.
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
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
86 * - row: An array containing information about the current row.
88 function template_preprocess_views_view_fields(&$variables) {
89 $view = $variables['view'];
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;
108 $object->element_type = $object->handler->elementType(TRUE, !$variables['options']['default_field_elements'], $object->inline);
109 if ($object->element_type) {
111 if ($object->handler->options['element_default_classes']) {
112 $attributes['class'][] = 'field-content';
115 if ($classes = $object->handler->elementClasses($row->index)) {
116 $attributes['class'][] = $classes;
118 $object->element_attributes = new Attribute($attributes);
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};
126 $object->raw = NULL; // make sure it exists to reduce NOTICE
129 if (!empty($variables['options']['separator']) && $previous_inline && $object->inline && $object->content) {
130 $object->separator = Xss::filterAdmin($variables['options']['separator']);
133 $object->class = Html::cleanCssIdentifier($id);
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';
142 // Set up field wrapper attributes if field wrapper was set.
143 if ($object->wrapper_element) {
145 if ($object->handler->options['element_default_classes']) {
146 $attributes['class'][] = 'views-field';
147 $attributes['class'][] = 'views-field-' . $object->class;
150 if ($classes = $object->handler->elementWrapperClasses($row->index)) {
151 $attributes['class'][] = $classes;
153 $object->wrapper_attributes = new Attribute($attributes);
156 // Set up field label
157 $object->label = $view->field[$id]->label();
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;
167 // Set up label HTML element.
168 $object->label_element = $object->handler->elementLabelType(TRUE, !$variables['options']['default_field_elements']);
170 // Set up label attributes.
171 if ($object->label_element) {
173 if ($object->handler->options['element_default_classes']) {
174 $attributes['class'][] = 'views-label';
175 $attributes['class'][] = 'views-label-' . $object->class;
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;
183 $object->label_attributes = new Attribute($attributes);
187 $variables['fields'][$id] = $object;
194 * Prepares variables for views single grouping templates.
196 * Default template: views-view-grouping.html.twig.
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
204 * - content: The content to be grouped.
205 * - title: The group heading.
207 function template_preprocess_views_view_grouping(&$variables) {
208 $variables['content'] = $variables['view']->style_plugin->renderGroupingSets($variables['rows'], $variables['grouping_level']);
212 * Prepares variables for views field templates.
214 * Default template: views-view-field.html.twig.
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
221 * - view: Instance of the ViewExecutable object for the parent view.
223 function template_preprocess_views_view_field(&$variables) {
224 $variables['output'] = $variables['field']->advancedRender($variables['row']);
228 * Prepares variables for views summary templates.
230 * The summary prints a single record from a row, with fields.
232 * Default template: views-view-summary.html.twig.
234 * @param array $variables
235 * An associative array containing:
236 * - view: A ViewExecutable object.
237 * - rows: The raw row data.
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']];
246 if (!empty($view->exposed_raw_input)) {
247 $url_options['query'] = $view->exposed_raw_input;
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(),
260 $active_urls = array_combine($active_urls, $active_urls);
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.
267 foreach ($variables['rows'] as $id => $row) {
268 $row_args[$id] = $argument->summaryArgument($row);
270 $argument->processSummaryArguments($row_args);
272 foreach ($variables['rows'] as $id => $row) {
273 $variables['rows'][$id]->attributes = [];
274 $variables['rows'][$id]->link = $argument->summaryName($row);
276 $args[$argument->position] = $row_args[$id];
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);
286 /** @var \Symfony\Component\Routing\Route $route */
287 $route_name = $url->getRouteName();
288 $route = \Drupal::service('router.route_provider')->getRouteByName($route_name);
290 $route_variables = $route->compile()->getVariables();
291 $parameters = $url->getRouteParameters();
293 foreach ($route_variables as $variable_name) {
294 $parameters[$variable_name] = array_shift($args);
297 $url->setRouteParameters($parameters);
299 catch (Exception $e) {
300 // If the given route doesn't exist, default to <front>
301 $url = Url::fromRoute('<front>');
305 $url = $view->getUrl($args)->setOptions($url_options);
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]);
315 * Prepares variables for unformatted summary view templates.
317 * Default template: views-view-summary-unformatted.html.twig.
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
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']];
334 if (!empty($view->exposed_raw_input)) {
335 $url_options['query'] = $view->exposed_raw_input;
340 // Force system path.
341 \Drupal::url('<current>', [], ['alias' => TRUE]),
342 // Could be an alias.
343 \Drupal::url('<current>'),
345 $active_urls = array_combine($active_urls, $active_urls);
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.
351 foreach ($variables['rows'] as $id => $row) {
352 $row_args[$id] = $argument->summaryArgument($row);
354 $argument->processSummaryArguments($row_args);
356 foreach ($variables['rows'] as $id => $row) {
357 // Only false on first time.
359 $variables['rows'][$id]->separator = Xss::filterAdmin($variables['options']['separator']);
361 $variables['rows'][$id]->attributes = [];
362 $variables['rows'][$id]->link = $argument->summaryName($row);
364 $args[$argument->position] = $row_args[$id];
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);
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();
379 foreach ($route_variables as $variable_name) {
380 $parameters[$variable_name] = array_shift($args);
383 $url->setRouteParameters($parameters);
385 catch (Exception $e) {
386 // If the given route doesn't exist, default to <front>
387 $url = Url::fromRoute('<front>');
391 $url = $view->getUrl($args)->setOptions($url_options);
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);
401 * Prepares variables for views table templates.
403 * Default template: views-view-table.html.twig.
405 * @param array $variables
406 * An associative array containing:
407 * - view: A ViewExecutable object.
408 * - rows: The raw row data.
410 function template_preprocess_views_view_table(&$variables) {
411 $view = $variables['view'];
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'] = [];
423 $options = $view->style_plugin->options;
424 $handler = $view->style_plugin;
426 $fields = &$view->field;
427 $columns = $handler->sanitizeColumns($options['columns'], $fields);
429 $active = !empty($handler->active) ? $handler->active : '';
430 $order = !empty($handler->order) ? $handler->order : 'asc';
432 // A boolean variable which stores whether the table has a responsive class.
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
439 $route_name = !empty($view->live_preview) ? '<current>' : '<none>';
441 $query = tablesort_get_query_parameters();
442 if (isset($view->exposed_raw_input)) {
443 $query += $view->exposed_raw_input;
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';
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;
463 $initial = !empty($options['info'][$field]['default_sort_order']) ? $options['info'][$field]['default_sort_order'] : 'asc';
465 if ($active == $field) {
466 $initial = ($order == 'asc') ? 'desc' : 'asc';
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,
477 $query['order'] = $field;
478 $query['sort'] = $initial;
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;
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);
493 $variables['header'][$field]['attributes']['class'][] = $class;
495 // Add responsive header classes.
496 if (!empty($options['info'][$field]['responsive'])) {
497 $variables['header'][$field]['attributes']['class'][] = $options['info'][$field]['responsive'];
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']);
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;
510 // Improves accessibility of complex tables.
511 $variables['header'][$field]['attributes']['id'] = Html::getUniqueId('view-' . $field . '-table-column');
513 // Check if header label is not empty.
514 if (!empty($variables['header'][$field]['content'])) {
515 $has_header_labels = TRUE;
518 $variables['header'][$field]['attributes'] = new Attribute($variables['header'][$field]['attributes']);
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']);
526 // Render each field into its appropriate column.
527 foreach ($result as $num => $row) {
529 // Skip building the attributes and content if the field is to be excluded
531 if (!empty($fields[$field]->options['exclude'])) {
535 // Reference to the column in the loop to make the code easier to read.
536 $column_reference =& $variables['rows'][$num]['columns'][$column];
538 $column_reference['default_classes'] = $fields[$field]->options['element_default_classes'];
540 // Set the field key to the column so it can be used for adding classes
542 $column_reference['fields'][] = $variables['fields'][$field];
544 // Add field classes.
545 if (!isset($column_reference['attributes'])) {
546 $column_reference['attributes'] = [];
549 if ($classes = $fields[$field]->elementClasses($num)) {
550 $column_reference['attributes']['class'][] = $classes;
553 // Add responsive header classes.
554 if (!empty($options['info'][$field]['responsive'])) {
555 $column_reference['attributes']['class'][] = $options['info'][$field]['responsive'];
558 // Improves accessibility of complex tables.
559 if (isset($variables['header'][$field]['attributes']['id'])) {
560 $column_reference['attributes']['headers'] = [$variables['header'][$field]['attributes']['id']];
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'] = [];
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]
580 $column_reference['content'][] = [
581 'field_output' => ['#markup' => $field_output]
586 $column_reference['attributes'] = new Attribute($column_reference['attributes']);
589 // Remove columns if the "empty_column" option is checked and the
591 if (!empty($options['info'][$field]['empty_column'])) {
593 foreach ($variables['rows'] as $columns) {
594 $empty &= empty($columns['columns'][$column]['content']);
597 foreach ($variables['rows'] as &$column_items) {
598 unset($column_items['columns'][$column]);
600 unset($variables['header'][$column]);
605 // Hide table header if all labels are empty.
606 if (!$has_header_labels) {
607 $variables['header'] = [];
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;
615 $variables['rows'][$num]['attributes'] = new Attribute($variables['rows'][$num]['attributes']);
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'],
629 $variables['sticky'] = FALSE;
630 if (!empty($options['sticky'])) {
631 $variables['view']->element['#attached']['library'][] = 'core/drupal.tableheader';
632 $variables['sticky'] = TRUE;
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;
640 elseif (!empty($variables['title'])) {
641 $variables['caption'] = ['#markup' => $variables['title']];
642 $variables['caption_needed'] = TRUE;
645 $variables['caption'] = '';
646 $variables['caption_needed'] = FALSE;
649 $variables['summary'] = $handler->options['summary'];
650 $variables['description'] = $handler->options['description'];
651 $variables['caption_needed'] |= !empty($variables['summary']) || !empty($variables['description']);
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;
666 * Prepares variables for views grid style templates.
668 * Default template: views-view-grid.html.twig.
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.
675 function template_preprocess_views_view_grid(&$variables) {
676 $options = $variables['options'] = $variables['view']->style_plugin->options;
677 $horizontal = ($options['alignment'] === 'horizontal');
682 $remainders = count($variables['rows']) % $options['columns'];
683 $num_rows = floor(count($variables['rows']) / $options['columns']);
685 // Iterate over each rendered views result row.
686 foreach ($variables['rows'] as $result_index => $item) {
690 $items[$row]['content'][$col]['content'] = $item;
693 $items[$col]['content'][$row]['content'] = $item;
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);
704 // Add row attributes to the item.
706 $items[$row]['attributes'] = new Attribute($row_attributes);
709 $items[$col]['content'][$row]['attributes'] = new Attribute($row_attributes);
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);
722 // Add automatic width for columns.
723 if ($options['automatic_width']) {
724 $col_attributes['style'] = 'width: ' . (100 / $options['columns']) . '%;';
726 // Add column attributes to the item.
728 $items[$row]['content'][$col]['attributes'] = new Attribute($col_attributes);
731 $items[$col]['attributes'] = new Attribute($col_attributes);
735 // Increase, decrease or reset appropriate integers.
737 if ($col == 0 && $col != ($options['columns'] - 1)) {
740 elseif ($col >= ($options['columns'] - 1)) {
750 if (!$remainders && $row == $num_rows) {
754 elseif ($remainders && $row == $num_rows + 1) {
762 // Add items to the variables array.
763 $variables['items'] = $items;
767 * Prepares variables for views unformatted rows templates.
769 * Default template: views-view-unformatted.html.twig.
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.
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;
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);
794 * Prepares variables for Views HTML list templates.
796 * Default template: views-view-list.html.twig.
798 * @param array $variables
799 * An associative array containing:
800 * - view: A View object.
802 function template_preprocess_views_view_list(&$variables) {
803 $handler = $variables['view']->style_plugin;
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);
810 // Initialize a new attribute class for $class.
811 $variables['list']['attributes'] = new Attribute(['class' => $class]);
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);
820 $variables['list']['type'] = $handler->options['type'];
822 template_preprocess_views_view_unformatted($variables);
826 * Prepares variables for RSS feed templates.
828 * Default template: views-view-rss.html.twig.
830 * @param array $variables
831 * An associative array containing:
832 * - view: A ViewExecutable object.
833 * - rows: The raw row data.
835 function template_preprocess_views_view_rss(&$variables) {
836 $view = $variables['view'];
837 $items = $variables['rows'];
838 $style = $view->style_plugin;
840 $config = \Drupal::config('system.site');
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 & becoming &amp;).
845 $variables['description'] = Html::decodeEntities(strip_tags($style->getDescription()));
847 if ($view->display_handler->getOption('sitename_title')) {
848 $title = $config->get('name');
849 if ($slogan = $config->get('slogan')) {
850 $title .= ' - ' . $slogan;
854 $title = $view->getTitle();
856 $variables['title'] = $title;
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);
866 /** @var \Drupal\Core\Url $url */
868 $url_options = ['absolute' => TRUE];
869 if (!empty($view->exposed_raw_input)) {
870 $url_options['query'] = $view->exposed_raw_input;
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();
880 $variables['link'] = $url_string;
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);
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');
896 * Prepares variables for views RSS item templates.
898 * Default template: views-view-row-rss.html.twig.
900 * @param array $variables
901 * An associative array containing:
902 * - row: The raw results rows.
904 function template_preprocess_views_view_row_rss(&$variables) {
905 $item = $variables['row'];
906 $variables['title'] = $item->title;
907 $variables['link'] = $item->link;
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);
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']);
922 $variables['item_elements'][] = $element;
927 * Prepares variables for OPML feed templates.
929 * Default template: views-view-opml.html.twig.
931 * @param array $variables
932 * An associative array containing:
933 * - view: A ViewExecutable object.
934 * - rows: The raw row data.
936 function template_preprocess_views_view_opml(&$variables) {
937 $view = $variables['view'];
938 $items = $variables['rows'];
940 $config = \Drupal::config('system.site');
942 if ($view->display_handler->getOption('sitename_title')) {
943 $title = $config->get('name');
944 if ($slogan = $config->get('slogan')) {
945 $title .= ' - ' . $slogan;
949 $title = $view->getTitle();
951 $variables['title'] = $title;
952 $variables['items'] = $items;
953 $variables['updated'] = gmdate(DATE_RFC2822, REQUEST_TIME);
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');
963 * Prepares variables for views OPML item templates.
965 * Default template: views-view-row-opml.html.twig.
967 * @param array $variables
968 * An associative array containing:
969 * - row: The raw results rows.
971 function template_preprocess_views_view_row_opml(&$variables) {
972 $item = $variables['row'];
974 $variables['attributes'] = new Attribute($item);
978 * Prepares variables for views exposed form templates.
980 * Default template: views-exposed-form.html.twig.
982 * @param array $variables
983 * An associative array containing:
984 * - form: A render element representing the form.
986 function template_preprocess_views_exposed_form(&$variables) {
987 $form = &$variables['form'];
989 if (!empty($form['q'])) {
990 $variables['q'] = $form['q'];
993 foreach ($form['#info'] as $info) {
994 if (!empty($info['label'])) {
995 $form[$info['value']]['#title'] = $info['label'];
997 if (!empty($info['description'])) {
998 $form[$info['value']]['#description'] = $info['description'];
1004 * Prepares variables for views mini-pager templates.
1006 * Default template: views-mini-pager.html.twig.
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
1015 function template_preprocess_views_mini_pager(&$variables) {
1016 global $pager_page_array, $pager_total;
1018 $tags = &$variables['tags'];
1019 $element = $variables['element'];
1020 $parameters = $variables['parameters'];
1022 // Current is the page we are currently paged to.
1023 $variables['items']['current'] = $pager_page_array[$element] + 1;
1025 if ($pager_total[$element] > 1 && $pager_page_array[$element] > 0) {
1027 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
1029 $variables['items']['previous']['href'] = \Drupal::url('<current>', [], $options);
1030 if (isset($tags[1])) {
1031 $variables['items']['previous']['text'] = $tags[1];
1033 $variables['items']['previous']['attributes'] = new Attribute();
1036 if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
1038 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
1040 $variables['items']['next']['href'] = \Drupal::url('<current>', [], $options);
1041 if (isset($tags[3])) {
1042 $variables['items']['next']['text'] = $tags[3];
1044 $variables['items']['next']['attributes'] = new Attribute();
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';
1053 * @defgroup views_templates Views template files
1055 * Describes various views templates & overriding options.
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.
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.
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.
1069 * The default style for all views is views-view-unformatted.html.twig.
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.
1074 * Here is an example of all the templates that will be tried in the following
1077 * View, named foobar. Style: unformatted. Row style: Fields. Display: Page.
1079 * - views-view--foobar--page.html.twig
1080 * - views-view--page.html.twig
1081 * - views-view--foobar.html.twig
1082 * - views-view.html.twig
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
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
1094 * Important! When adding a new template to your theme, be sure to flush the
1095 * theme registry cache!
1097 * @ingroup views_overview
1098 * @see \Drupal\views\ViewExecutable::buildThemeFunctions()