views.theme.inc 40 KB

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