views.theme.inc 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099
  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. if ($link_display_id && $display = $view->displayHandlers->get($link_display_id)) {
  760. $url = $view->getUrl(NULL, $link_display_id);
  761. }
  762. /** @var \Drupal\Core\Url $url */
  763. if ($url) {
  764. $url_options = ['absolute' => TRUE];
  765. if (!empty($view->exposed_raw_input)) {
  766. $url_options['query'] = $view->exposed_raw_input;
  767. }
  768. // Compare the link to the default home page; if it's the default home page,
  769. // just use $base_url.
  770. $url_string = $url->setOptions($url_options)->toString();
  771. if ($url_string === Url::fromUserInput($config->get('page.front'))->toString()) {
  772. $url_string = Url::fromRoute('<front>')->setAbsolute()->toString();
  773. }
  774. $variables['link'] = $url_string;
  775. }
  776. $variables['langcode'] = \Drupal::languageManager()->getCurrentLanguage()->getId();
  777. $variables['namespaces'] = new Attribute($style->namespaces);
  778. $variables['items'] = $items;
  779. $variables['channel_elements'] = \Drupal::service('renderer')->render($style->channel_elements);
  780. // During live preview we don't want to output the header since the contents
  781. // of the feed are being displayed inside a normal HTML page.
  782. if (empty($variables['view']->live_preview)) {
  783. $variables['view']->getResponse()->headers->set('Content-Type', 'application/rss+xml; charset=utf-8');
  784. }
  785. }
  786. /**
  787. * Prepares variables for views RSS item templates.
  788. *
  789. * Default template: views-view-row-rss.html.twig.
  790. *
  791. * @param array $variables
  792. * An associative array containing:
  793. * - row: The raw results rows.
  794. */
  795. function template_preprocess_views_view_row_rss(&$variables) {
  796. $item = $variables['row'];
  797. $variables['title'] = $item->title;
  798. $variables['link'] = $item->link;
  799. // The description is the only place where we should find HTML.
  800. // @see https://validator.w3.org/feed/docs/rss2.html#hrelementsOfLtitemgt
  801. // If we have a render array, render it here and pass the result to the
  802. // template, letting Twig autoescape it.
  803. if (isset($item->description) && is_array($item->description)) {
  804. $variables['description'] = (string) \Drupal::service('renderer')->render($item->description);
  805. }
  806. $variables['item_elements'] = [];
  807. foreach ($item->elements as $element) {
  808. if (isset($element['attributes']) && is_array($element['attributes'])) {
  809. $element['attributes'] = new Attribute($element['attributes']);
  810. }
  811. $variables['item_elements'][] = $element;
  812. }
  813. }
  814. /**
  815. * Prepares variables for OPML feed templates.
  816. *
  817. * Default template: views-view-opml.html.twig.
  818. *
  819. * @param array $variables
  820. * An associative array containing:
  821. * - view: A ViewExecutable object.
  822. * - rows: The raw row data.
  823. */
  824. function template_preprocess_views_view_opml(&$variables) {
  825. $view = $variables['view'];
  826. $items = $variables['rows'];
  827. $config = \Drupal::config('system.site');
  828. if ($view->display_handler->getOption('sitename_title')) {
  829. $title = $config->get('name');
  830. if ($slogan = $config->get('slogan')) {
  831. $title .= ' - ' . $slogan;
  832. }
  833. }
  834. else {
  835. $title = $view->getTitle();
  836. }
  837. $variables['title'] = $title;
  838. $variables['items'] = $items;
  839. $variables['updated'] = gmdate(DATE_RFC2822, REQUEST_TIME);
  840. // During live preview we don't want to output the header since the contents
  841. // of the feed are being displayed inside a normal HTML page.
  842. if (empty($variables['view']->live_preview)) {
  843. $variables['view']->getResponse()->headers->set('Content-Type', 'text/xml; charset=utf-8');
  844. }
  845. }
  846. /**
  847. * Prepares variables for views OPML item templates.
  848. *
  849. * Default template: views-view-row-opml.html.twig.
  850. *
  851. * @param array $variables
  852. * An associative array containing:
  853. * - row: The raw results rows.
  854. */
  855. function template_preprocess_views_view_row_opml(&$variables) {
  856. $item = $variables['row'];
  857. $variables['attributes'] = new Attribute($item);
  858. }
  859. /**
  860. * Prepares variables for views exposed form templates.
  861. *
  862. * Default template: views-exposed-form.html.twig.
  863. *
  864. * @param array $variables
  865. * An associative array containing:
  866. * - form: A render element representing the form.
  867. */
  868. function template_preprocess_views_exposed_form(&$variables) {
  869. $form = &$variables['form'];
  870. if (!empty($form['q'])) {
  871. $variables['q'] = $form['q'];
  872. }
  873. foreach ($form['#info'] as $info) {
  874. if (!empty($info['label'])) {
  875. $form[$info['value']]['#title'] = $info['label'];
  876. }
  877. if (!empty($info['description'])) {
  878. $form[$info['value']]['#description'] = $info['description'];
  879. }
  880. }
  881. }
  882. /**
  883. * Prepares variables for views mini-pager templates.
  884. *
  885. * Default template: views-mini-pager.html.twig.
  886. *
  887. * @param array $variables
  888. * An associative array containing:
  889. * - tags: Provides link text for the next/previous links.
  890. * - element: The pager's id.
  891. * - parameters: Any extra GET parameters that should be retained, such as
  892. * exposed input.
  893. */
  894. function template_preprocess_views_mini_pager(&$variables) {
  895. global $pager_page_array, $pager_total;
  896. $tags = &$variables['tags'];
  897. $element = $variables['element'];
  898. $parameters = $variables['parameters'];
  899. // Current is the page we are currently paged to.
  900. $variables['items']['current'] = $pager_page_array[$element] + 1;
  901. if ($pager_total[$element] > 1 && $pager_page_array[$element] > 0) {
  902. $options = [
  903. 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] - 1),
  904. ];
  905. $variables['items']['previous']['href'] = \Drupal::url('<current>', [], $options);
  906. if (isset($tags[1])) {
  907. $variables['items']['previous']['text'] = $tags[1];
  908. }
  909. $variables['items']['previous']['attributes'] = new Attribute();
  910. }
  911. if ($pager_page_array[$element] < ($pager_total[$element] - 1)) {
  912. $options = [
  913. 'query' => pager_query_add_page($parameters, $element, $pager_page_array[$element] + 1),
  914. ];
  915. $variables['items']['next']['href'] = \Drupal::url('<current>', [], $options);
  916. if (isset($tags[3])) {
  917. $variables['items']['next']['text'] = $tags[3];
  918. }
  919. $variables['items']['next']['attributes'] = new Attribute();
  920. }
  921. // This is based on the entire current query string. We need to ensure
  922. // cacheability is affected accordingly.
  923. $variables['#cache']['contexts'][] = 'url.query_args';
  924. }
  925. /**
  926. * @defgroup views_templates Views template files
  927. * @{
  928. * Describes various views templates & overriding options.
  929. *
  930. * All views templates can be overridden with a variety of names, using
  931. * the view, the display ID of the view, the display type of the view,
  932. * or some combination thereof.
  933. *
  934. * For each view, there will be a minimum of two templates used. The first
  935. * is used for all views: views-view.html.twig.
  936. *
  937. * The second template is determined by the style selected for the view. Note
  938. * that certain aspects of the view can also change which style is used; for
  939. * example, arguments which provide a summary view might change the style to
  940. * one of the special summary styles.
  941. *
  942. * The default style for all views is views-view-unformatted.html.twig.
  943. *
  944. * Many styles will then farm out the actual display of each row to a row
  945. * style; the default row style is views-view-fields.html.twig.
  946. *
  947. * Here is an example of all the templates that will be tried in the following
  948. * case:
  949. *
  950. * View, named foobar. Style: unformatted. Row style: Fields. Display: Page.
  951. *
  952. * - views-view--foobar--page.html.twig
  953. * - views-view--page.html.twig
  954. * - views-view--foobar.html.twig
  955. * - views-view.html.twig
  956. *
  957. * - views-view-unformatted--foobar--page.html.twig
  958. * - views-view-unformatted--page.html.twig
  959. * - views-view-unformatted--foobar.html.twig
  960. * - views-view-unformatted.html.twig
  961. *
  962. * - views-view-fields--foobar--page.html.twig
  963. * - views-view-fields--page.html.twig
  964. * - views-view-fields--foobar.html.twig
  965. * - views-view-fields.html.twig
  966. *
  967. * Important! When adding a new template to your theme, be sure to flush the
  968. * theme registry cache!
  969. *
  970. * @ingroup views_overview
  971. * @see \Drupal\views\ViewExecutable::buildThemeFunctions()
  972. * @}
  973. */