views.theme.inc 39 KB

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