views.theme.inc 39 KB

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