views.theme.inc 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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. $variables['summary_element'] = [
  588. '#type' => 'details',
  589. '#title' => $handler->options['summary'],
  590. // To ensure that the description is properly escaped during rendering, use
  591. // an 'inline_template' to let Twig do its magic, instead of 'markup'.
  592. 'description' => [
  593. '#type' => 'inline_template',
  594. '#template' => '{{ description }}',
  595. '#context' => [
  596. 'description' => $handler->options['description'],
  597. ],
  598. ],
  599. ];
  600. $variables['caption_needed'] |= !empty($variables['summary']) || !empty($variables['description']);
  601. $variables['responsive'] = FALSE;
  602. // If the table has headers and it should react responsively to columns hidden
  603. // with the classes represented by the constants RESPONSIVE_PRIORITY_MEDIUM
  604. // and RESPONSIVE_PRIORITY_LOW, add the tableresponsive behaviors.
  605. if (isset($variables['header']) && $responsive) {
  606. $variables['view']->element['#attached']['library'][] = 'core/drupal.tableresponsive';
  607. // Add 'responsive-enabled' class to the table to identify it for JS.
  608. // This is needed to target tables constructed by this function.
  609. $variables['responsive'] = TRUE;
  610. }
  611. }
  612. /**
  613. * Prepares variables for views grid style templates.
  614. *
  615. * Default template: views-view-grid.html.twig.
  616. *
  617. * @param array $variables
  618. * An associative array containing:
  619. * - view: The view object.
  620. * - rows: An array of row items. Each row is an array of content.
  621. */
  622. function template_preprocess_views_view_grid(&$variables) {
  623. $options = $variables['options'] = $variables['view']->style_plugin->options;
  624. $horizontal = ($options['alignment'] === 'horizontal');
  625. $col = 0;
  626. $row = 0;
  627. $items = [];
  628. $remainders = count($variables['rows']) % $options['columns'];
  629. $num_rows = floor(count($variables['rows']) / $options['columns']);
  630. // Iterate over each rendered views result row.
  631. foreach ($variables['rows'] as $result_index => $item) {
  632. // Add the item.
  633. if ($horizontal) {
  634. $items[$row]['content'][$col]['content'] = $item;
  635. }
  636. else {
  637. $items[$col]['content'][$row]['content'] = $item;
  638. }
  639. // Create attributes for rows.
  640. if (!$horizontal || ($horizontal && empty($items[$row]['attributes']))) {
  641. $row_attributes = ['class' => []];
  642. // Add custom row classes.
  643. $row_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'row')));
  644. if (!empty($row_class)) {
  645. $row_attributes['class'] = array_merge($row_attributes['class'], $row_class);
  646. }
  647. // Add row attributes to the item.
  648. if ($horizontal) {
  649. $items[$row]['attributes'] = new Attribute($row_attributes);
  650. }
  651. else {
  652. $items[$col]['content'][$row]['attributes'] = new Attribute($row_attributes);
  653. }
  654. }
  655. // Create attributes for columns.
  656. if ($horizontal || (!$horizontal && empty($items[$col]['attributes']))) {
  657. $col_attributes = ['class' => []];
  658. // Add default views column classes.
  659. // Add custom column classes.
  660. $col_class = array_filter(explode(' ', $variables['view']->style_plugin->getCustomClass($result_index, 'col')));
  661. if (!empty($col_class)) {
  662. $col_attributes['class'] = array_merge($col_attributes['class'], $col_class);
  663. }
  664. // Add automatic width for columns.
  665. if ($options['automatic_width']) {
  666. $col_attributes['style'] = 'width: ' . (100 / $options['columns']) . '%;';
  667. }
  668. // Add column attributes to the item.
  669. if ($horizontal) {
  670. $items[$row]['content'][$col]['attributes'] = new Attribute($col_attributes);
  671. }
  672. else {
  673. $items[$col]['attributes'] = new Attribute($col_attributes);
  674. }
  675. }
  676. // Increase, decrease or reset appropriate integers.
  677. if ($horizontal) {
  678. if ($col == 0 && $col != ($options['columns'] - 1)) {
  679. $col++;
  680. }
  681. elseif ($col >= ($options['columns'] - 1)) {
  682. $col = 0;
  683. $row++;
  684. }
  685. else {
  686. $col++;
  687. }
  688. }
  689. else {
  690. $row++;
  691. if (!$remainders && $row == $num_rows) {
  692. $row = 0;
  693. $col++;
  694. }
  695. elseif ($remainders && $row == $num_rows + 1) {
  696. $row = 0;
  697. $col++;
  698. $remainders--;
  699. }
  700. }
  701. }
  702. // Add items to the variables array.
  703. $variables['items'] = $items;
  704. }
  705. /**
  706. * Prepares variables for views unformatted rows templates.
  707. *
  708. * Default template: views-view-unformatted.html.twig.
  709. *
  710. * @param array $variables
  711. * An associative array containing:
  712. * - view: The view object.
  713. * - rows: An array of row items. Each row is an array of content.
  714. */
  715. function template_preprocess_views_view_unformatted(&$variables) {
  716. $view = $variables['view'];
  717. $rows = $variables['rows'];
  718. $style = $view->style_plugin;
  719. $options = $style->options;
  720. $variables['default_row_class'] = !empty($options['default_row_class']);
  721. foreach ($rows as $id => $row) {
  722. $variables['rows'][$id] = [];
  723. $variables['rows'][$id]['content'] = $row;
  724. $variables['rows'][$id]['attributes'] = new Attribute();
  725. if ($row_class = $view->style_plugin->getRowClass($id)) {
  726. $variables['rows'][$id]['attributes']->addClass($row_class);
  727. }
  728. }
  729. }
  730. /**
  731. * Prepares variables for Views HTML list templates.
  732. *
  733. * Default template: views-view-list.html.twig.
  734. *
  735. * @param array $variables
  736. * An associative array containing:
  737. * - view: A View object.
  738. */
  739. function template_preprocess_views_view_list(&$variables) {
  740. $handler = $variables['view']->style_plugin;
  741. // Fetch classes from handler options.
  742. if ($handler->options['class']) {
  743. $class = explode(' ', $handler->options['class']);
  744. $class = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $class);
  745. // Initialize a new attribute class for $class.
  746. $variables['list']['attributes'] = new Attribute(['class' => $class]);
  747. }
  748. // Fetch wrapper classes from handler options.
  749. if ($handler->options['wrapper_class']) {
  750. $wrapper_class = explode(' ', $handler->options['wrapper_class']);
  751. $variables['attributes']['class'] = array_map('\Drupal\Component\Utility\Html::cleanCssIdentifier', $wrapper_class);
  752. }
  753. $variables['list']['type'] = $handler->options['type'];
  754. template_preprocess_views_view_unformatted($variables);
  755. }
  756. /**
  757. * Prepares variables for RSS feed templates.
  758. *
  759. * Default template: views-view-rss.html.twig.
  760. *
  761. * @param array $variables
  762. * An associative array containing:
  763. * - view: A ViewExecutable object.
  764. * - rows: The raw row data.
  765. */
  766. function template_preprocess_views_view_rss(&$variables) {
  767. $view = $variables['view'];
  768. $items = $variables['rows'];
  769. $style = $view->style_plugin;
  770. $config = \Drupal::config('system.site');
  771. // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
  772. // We strip all HTML tags, but need to prevent double encoding from properly
  773. // escaped source data (such as &amp becoming &amp;amp;).
  774. $variables['description'] = Html::decodeEntities(strip_tags($style->getDescription()));
  775. if ($view->display_handler->getOption('sitename_title')) {
  776. $title = $config->get('name');
  777. if ($slogan = $config->get('slogan')) {
  778. $title .= ' - ' . $slogan;
  779. }
  780. }
  781. else {
  782. $title = $view->getTitle();
  783. }
  784. $variables['title'] = $title;
  785. $variables['link'] = Url::fromRoute('<front>')->setAbsolute()->toString();
  786. $variables['langcode'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
  787. $variables['namespaces'] = new Attribute($style->namespaces);
  788. $variables['items'] = $items;
  789. $variables['channel_elements'] = $style->channel_elements;
  790. // During live preview we don't want to output the header since the contents
  791. // of the feed are being displayed inside a normal HTML page.
  792. if (empty($variables['view']->live_preview)) {
  793. $variables['view']->getResponse()->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
  794. }
  795. }
  796. /**
  797. * Prepares variables for views RSS item templates.
  798. *
  799. * Default template: views-view-row-rss.html.twig.
  800. *
  801. * @param array $variables
  802. * An associative array containing:
  803. * - row: The raw results rows.
  804. */
  805. function template_preprocess_views_view_row_rss(&$variables) {
  806. $item = $variables['row'];
  807. $variables['title'] = $item->title;
  808. $variables['link'] = $item->link;
  809. // The description is the only place where we should find HTML.
  810. // @see https://validator.w3.org/feed/docs/rss2.html#hrelementsOfLtitemgt
  811. // If we have a render array, render it here and pass the result to the
  812. // template, letting Twig autoescape it.
  813. if (isset($item->description) && is_array($item->description)) {
  814. $variables['description'] = (string) \Drupal::service('renderer')->render($item->description);
  815. }
  816. $variables['item_elements'] = [];
  817. foreach ($item->elements as $element) {
  818. if (isset($element['attributes']) && is_array($element['attributes'])) {
  819. $element['attributes'] = new Attribute($element['attributes']);
  820. }
  821. $variables['item_elements'][] = $element;
  822. }
  823. }
  824. /**
  825. * Prepares variables for OPML feed templates.
  826. *
  827. * Default template: views-view-opml.html.twig.
  828. *
  829. * @param array $variables
  830. * An associative array containing:
  831. * - view: A ViewExecutable object.
  832. * - rows: The raw row data.
  833. */
  834. function template_preprocess_views_view_opml(&$variables) {
  835. $view = $variables['view'];
  836. $items = $variables['rows'];
  837. $config = \Drupal::config('system.site');
  838. if ($view->display_handler->getOption('sitename_title')) {
  839. $title = $config->get('name');
  840. if ($slogan = $config->get('slogan')) {
  841. $title .= ' - ' . $slogan;
  842. }
  843. }
  844. else {
  845. $title = $view->getTitle();
  846. }
  847. $variables['title'] = $title;
  848. $variables['items'] = $items;
  849. $variables['updated'] = gmdate(DATE_RFC2822, REQUEST_TIME);
  850. // During live preview we don't want to output the header since the contents
  851. // of the feed are being displayed inside a normal HTML page.
  852. if (empty($variables['view']->live_preview)) {
  853. $variables['view']->getResponse()->headers->set('Content-Type', 'text/xml; charset=utf-8');
  854. }
  855. }
  856. /**
  857. * Prepares variables for views OPML item templates.
  858. *
  859. * Default template: views-view-row-opml.html.twig.
  860. *
  861. * @param array $variables
  862. * An associative array containing:
  863. * - row: The raw results rows.
  864. */
  865. function template_preprocess_views_view_row_opml(&$variables) {
  866. $item = $variables['row'];
  867. $variables['attributes'] = new Attribute($item);
  868. }
  869. /**
  870. * Prepares variables for views exposed form templates.
  871. *
  872. * Default template: views-exposed-form.html.twig.
  873. *
  874. * @param array $variables
  875. * An associative array containing:
  876. * - form: A render element representing the form.
  877. */
  878. function template_preprocess_views_exposed_form(&$variables) {
  879. $form = &$variables['form'];
  880. if (!empty($form['q'])) {
  881. $variables['q'] = $form['q'];
  882. }
  883. foreach ($form['#info'] as $info) {
  884. if (!empty($info['label'])) {
  885. $form[$info['value']]['#title'] = $info['label'];
  886. }
  887. if (!empty($info['description'])) {
  888. $form[$info['value']]['#description'] = $info['description'];
  889. }
  890. }
  891. }
  892. /**
  893. * Prepares variables for views mini-pager templates.
  894. *
  895. * Default template: views-mini-pager.html.twig.
  896. *
  897. * @param array $variables
  898. * An associative array containing:
  899. * - tags: Provides link text for the next/previous links.
  900. * - element: The pager's id.
  901. * - parameters: Any extra GET parameters that should be retained, such as
  902. * exposed input.
  903. */
  904. function template_preprocess_views_mini_pager(&$variables) {
  905. /* @var $pager_manager \Drupal\Core\Pager\PagerManagerInterface */
  906. $pager_manager = \Drupal::service('pager.manager');
  907. $tags = &$variables['tags'];
  908. $element = $variables['element'];
  909. $parameters = $variables['parameters'];
  910. $pager = $pager_manager->getPager($element);
  911. if (!$pager) {
  912. return;
  913. }
  914. $current = $pager->getCurrentPage();
  915. $total = $pager->getTotalPages();
  916. // Current is the page we are currently paged to.
  917. $variables['items']['current'] = $current + 1;
  918. if ($total > 1 && $current > 0) {
  919. $options = [
  920. 'query' => $pager_manager->getUpdatedParameters($parameters, $element, $current - 1),
  921. ];
  922. $variables['items']['previous']['href'] = Url::fromRoute('<current>', [], $options)->toString();
  923. if (isset($tags[1])) {
  924. $variables['items']['previous']['text'] = $tags[1];
  925. }
  926. $variables['items']['previous']['attributes'] = new Attribute();
  927. }
  928. if ($current < ($total - 1)) {
  929. $options = [
  930. 'query' => $pager_manager->getUpdatedParameters($parameters, $element, $current + 1),
  931. ];
  932. $variables['items']['next']['href'] = Url::fromRoute('<current>', [], $options)->toString();
  933. if (isset($tags[3])) {
  934. $variables['items']['next']['text'] = $tags[3];
  935. }
  936. $variables['items']['next']['attributes'] = new Attribute();
  937. }
  938. // This is based on the entire current query string. We need to ensure
  939. // cacheability is affected accordingly.
  940. $variables['#cache']['contexts'][] = 'url.query_args';
  941. $variables['heading_id'] = Html::getUniqueId('pagination-heading');
  942. }
  943. /**
  944. * @defgroup views_templates Views template files
  945. * @{
  946. * Describes various views templates & overriding options.
  947. *
  948. * All views templates can be overridden with a variety of names, using
  949. * the view, the display ID of the view, the display type of the view,
  950. * or some combination thereof.
  951. *
  952. * For each view, there will be a minimum of two templates used. The first
  953. * is used for all views: views-view.html.twig.
  954. *
  955. * The second template is determined by the style selected for the view. Note
  956. * that certain aspects of the view can also change which style is used; for
  957. * example, arguments which provide a summary view might change the style to
  958. * one of the special summary styles.
  959. *
  960. * The default style for all views is views-view-unformatted.html.twig.
  961. *
  962. * Many styles will then farm out the actual display of each row to a row
  963. * style; the default row style is views-view-fields.html.twig.
  964. *
  965. * Here is an example of all the templates that will be tried in the following
  966. * case:
  967. *
  968. * View, named foobar. Style: unformatted. Row style: Fields. Display: Page.
  969. *
  970. * - views-view--foobar--page.html.twig
  971. * - views-view--page.html.twig
  972. * - views-view--foobar.html.twig
  973. * - views-view.html.twig
  974. *
  975. * - views-view-unformatted--foobar--page.html.twig
  976. * - views-view-unformatted--page.html.twig
  977. * - views-view-unformatted--foobar.html.twig
  978. * - views-view-unformatted.html.twig
  979. *
  980. * - views-view-fields--foobar--page.html.twig
  981. * - views-view-fields--page.html.twig
  982. * - views-view-fields--foobar.html.twig
  983. * - views-view-fields.html.twig
  984. *
  985. * Important! When adding a new template to your theme, be sure to flush the
  986. * theme registry cache!
  987. *
  988. * @ingroup views_overview
  989. * @see \Drupal\views\ViewExecutable::buildThemeFunctions()
  990. * @}
  991. */