views.theme.inc 40 KB

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