theme.api.php 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. <?php
  2. /**
  3. * @file
  4. * Hooks and documentation related to the theme and render system.
  5. */
  6. /**
  7. * @defgroup themeable Theme system overview
  8. * @{
  9. * Functions and templates for the user interface that themes can override.
  10. *
  11. * Drupal's theme system allows a theme to have nearly complete control over
  12. * the appearance of the site, which includes both the markup and the CSS used
  13. * to style the markup. For this system to work, modules, instead of writing
  14. * HTML markup directly, need to return "render arrays", which are structured
  15. * hierarchical arrays that include the data to be rendered into HTML (or XML or
  16. * another output format), and options that affect the markup. Render arrays
  17. * are ultimately rendered into HTML or other output formats by recursive calls
  18. * to drupal_render(), traversing the depth of the render array hierarchy. At
  19. * each level, the theme system is invoked to do the actual rendering. See the
  20. * documentation of drupal_render() and the
  21. * @link theme_render Theme system and Render API topic @endlink for more
  22. * information about render arrays and rendering.
  23. *
  24. * @section sec_twig_theme Twig Templating Engine
  25. * Drupal 8 uses the templating engine Twig. Twig offers developers a fast,
  26. * secure, and flexible method for building templates for Drupal 8 sites. Twig
  27. * also offers substantial usability improvements over PHPTemplate, and does
  28. * not require front-end developers to know PHP to build and manipulate Drupal
  29. * 8 themes.
  30. *
  31. * For further information on theming in Drupal 8 see
  32. * https://www.drupal.org/docs/8/theming
  33. *
  34. * For further Twig documentation see
  35. * https://twig.symfony.com/doc/1.x/templates.html
  36. *
  37. * @section sec_theme_hooks Theme Hooks
  38. * The theme system is invoked in \Drupal\Core\Render\Renderer::doRender() by
  39. * calling the \Drupal\Core\Theme\ThemeManagerInterface::render() function,
  40. * which operates on the concept of "theme hooks". Theme hooks define how a
  41. * particular type of data should be rendered. They are registered by modules by
  42. * implementing hook_theme(), which specifies the name of the hook, the input
  43. * "variables" used to provide data and options, and other information. Modules
  44. * implementing hook_theme() also need to provide a default implementation for
  45. * each of their theme hooks, normally in a Twig file, and they may also provide
  46. * preprocessing functions. For example, the core Search module defines a theme
  47. * hook for a search result item in search_theme():
  48. * @code
  49. * return array(
  50. * 'search_result' => array(
  51. * 'variables' => array(
  52. * 'result' => NULL,
  53. * 'plugin_id' => NULL,
  54. * ),
  55. * 'file' => 'search.pages.inc',
  56. * ),
  57. * );
  58. * @endcode
  59. * Given this definition, the template file with the default implementation is
  60. * search-result.html.twig, which can be found in the
  61. * core/modules/search/templates directory, and the variables for rendering are
  62. * the search result and the plugin ID. In addition, there is a function
  63. * template_preprocess_search_result(), located in file search.pages.inc, which
  64. * preprocesses the information from the input variables so that it can be
  65. * rendered by the Twig template; the processed variables that the Twig template
  66. * receives are documented in the header of the default Twig template file.
  67. *
  68. * hook_theme() implementations can also specify that a theme hook
  69. * implementation is a theme function, but that is uncommon and not recommended.
  70. * Note that while Twig templates will auto-escape variables, theme functions
  71. * must explicitly escape any variables by using theme_render_and_autoescape().
  72. * Failure to do so is likely to result in security vulnerabilities. Theme
  73. * functions are deprecated in Drupal 8.0.x and will be removed before
  74. * Drupal 9.0.x. Use Twig templates instead.
  75. *
  76. * @section sec_overriding_theme_hooks Overriding Theme Hooks
  77. * Themes may register new theme hooks within a hook_theme() implementation, but
  78. * it is more common for themes to override default implementations provided by
  79. * modules than to register entirely new theme hooks. Themes can override a
  80. * default implementation by creating a template file with the same name as the
  81. * default implementation; for example, to override the display of search
  82. * results, a theme would add a file called search-result.html.twig to its
  83. * templates directory. A good starting point for doing this is normally to
  84. * copy the default implementation template, and then modifying it as desired.
  85. *
  86. * In the uncommon case that a theme hook uses a theme function instead of a
  87. * template file, a module would provide a default implementation function
  88. * called theme_HOOK, where HOOK is the name of the theme hook (for example,
  89. * theme_search_result() would be the name of the function for search result
  90. * theming). In this case, a theme can override the default implementation by
  91. * defining a function called THEME_HOOK() in its THEME.theme file, where THEME
  92. * is the machine name of the theme (for example, 'bartik' is the machine name
  93. * of the core Bartik theme, and it would define a function called
  94. * bartik_search_result() in the bartik.theme file, if the search_result hook
  95. * implementation was a function instead of a template). Normally, copying the
  96. * default function is again a good starting point for overriding its behavior.
  97. * Again, note that theme functions (unlike templates) must explicitly escape
  98. * variables using theme_render_and_autoescape() or risk security
  99. * vulnerabilities. Theme functions are deprecated in Drupal 8.0.x and will be
  100. * removed before Drupal 9.0.x. Use Twig templates instead.
  101. *
  102. * @section sec_preprocess_templates Preprocessing for Template Files
  103. * If the theme implementation is a template file, several functions are called
  104. * before the template file is invoked to modify the variables that are passed
  105. * to the template. These make up the "preprocessing" phase, and are executed
  106. * (if they exist), in the following order (note that in the following list,
  107. * HOOK indicates the hook being called or a less specific hook. For example, if
  108. * '#theme' => 'node__article' is called, hook is node__article and node. MODULE
  109. * indicates a module name, THEME indicates a theme name, and ENGINE indicates a
  110. * theme engine name). Modules, themes, and theme engines can provide these
  111. * functions to modify how the data is preprocessed, before it is passed to the
  112. * theme template:
  113. * - template_preprocess(&$variables, $hook): Creates a default set of variables
  114. * for all theme hooks with template implementations. Provided by Drupal Core.
  115. * - template_preprocess_HOOK(&$variables): Should be implemented by the module
  116. * that registers the theme hook, to set up default variables.
  117. * - MODULE_preprocess(&$variables, $hook): hook_preprocess() is invoked on all
  118. * implementing modules.
  119. * - MODULE_preprocess_HOOK(&$variables): hook_preprocess_HOOK() is invoked on
  120. * all implementing modules, so that modules that didn't define the theme hook
  121. * can alter the variables.
  122. * - ENGINE_engine_preprocess(&$variables, $hook): Allows the theme engine to
  123. * set necessary variables for all theme hooks with template implementations.
  124. * - ENGINE_engine_preprocess_HOOK(&$variables): Allows the theme engine to set
  125. * necessary variables for the particular theme hook.
  126. * - THEME_preprocess(&$variables, $hook): Allows the theme to set necessary
  127. * variables for all theme hooks with template implementations.
  128. * - THEME_preprocess_HOOK(&$variables): Allows the theme to set necessary
  129. * variables specific to the particular theme hook.
  130. *
  131. * @section sec_preprocess_functions Preprocessing for Theme Functions
  132. * If the theming implementation is a function, only the theme-hook-specific
  133. * preprocess functions (the ones ending in _HOOK) are called from the list
  134. * above. This is because theme hooks with function implementations need to be
  135. * fast, and calling the non-theme-hook-specific preprocess functions for them
  136. * would incur a noticeable performance penalty.
  137. *
  138. * @section sec_suggestions Theme hook suggestions
  139. * In some cases, instead of calling the base theme hook implementation (either
  140. * the default provided by the module that defined the hook, or the override
  141. * provided by the theme), the theme system will instead look for "suggestions"
  142. * of other hook names to look for. Suggestions can be specified in several
  143. * ways:
  144. * - In a render array, the '#theme' property (which gives the name of the hook
  145. * to use) can be an array of theme hook names instead of a single hook name.
  146. * In this case, the render system will look first for the highest-priority
  147. * hook name, and if no implementation is found, look for the second, and so
  148. * on. Note that the highest-priority suggestion is at the end of the array.
  149. * - In a render array, the '#theme' property can be set to the name of a hook
  150. * with a '__SUGGESTION' suffix. For example, in search results theming, the
  151. * hook 'item_list__search_results' is given. In this case, the render system
  152. * will look for theme templates called item-list--search-results.html.twig,
  153. * which would only be used for rendering item lists containing search
  154. * results, and if this template is not found, it will fall back to using the
  155. * base item-list.html.twig template. This type of suggestion can also be
  156. * combined with providing an array of theme hook names as described above.
  157. * - A module can implement hook_theme_suggestions_HOOK(). This allows the
  158. * module that defines the theme template to dynamically return an array
  159. * containing specific theme hook names (presumably with '__' suffixes as
  160. * defined above) to use as suggestions. For example, the Search module
  161. * does this in search_theme_suggestions_search_result() to suggest
  162. * search_result__PLUGIN as the theme hook for search result items, where
  163. * PLUGIN is the machine name of the particular search plugin type that was
  164. * used for the search (such as node_search or user_search).
  165. *
  166. * For further information on overriding theme hooks see
  167. * https://www.drupal.org/node/2186401
  168. *
  169. * @section sec_alternate_suggestions Altering theme hook suggestions
  170. * Modules can also alter the theme suggestions provided using the mechanisms
  171. * of the previous section. There are two hooks for this: the
  172. * theme-hook-specific hook_theme_suggestions_HOOK_alter() and the generic
  173. * hook_theme_suggestions_alter(). These hooks get the current list of
  174. * suggestions as input, and can change this array (adding suggestions and
  175. * removing them).
  176. *
  177. * @section assets Assets
  178. * We can distinguish between three types of assets:
  179. * - Unconditional page-level assets (loaded on all pages where the theme is in
  180. * use): these are defined in the theme's *.info.yml file.
  181. * - Conditional page-level assets (loaded on all pages where the theme is in
  182. * use and a certain condition is met): these are attached in
  183. * hook_page_attachments_alter(), e.g.:
  184. * @code
  185. * function THEME_page_attachments_alter(array &$page) {
  186. * if ($some_condition) {
  187. * $page['#attached']['library'][] = 'mytheme/something';
  188. * }
  189. * }
  190. * @endcode
  191. * - Template-specific assets (loaded on all pages where a specific template is
  192. * in use): these can be added by in preprocessing functions, using @code
  193. * $variables['#attached'] @endcode, e.g.:
  194. * @code
  195. * function THEME_preprocess_menu_local_action(array &$variables) {
  196. * // We require Modernizr's touch test for button styling.
  197. * $variables['#attached']['library'][] = 'core/modernizr';
  198. * }
  199. * @endcode
  200. *
  201. * @see hooks
  202. * @see callbacks
  203. * @see theme_render
  204. *
  205. * @}
  206. */
  207. /**
  208. * @defgroup theme_render Render API overview
  209. * @{
  210. * Overview of the Theme system and Render API.
  211. *
  212. * The main purpose of Drupal's Theme system is to give themes complete control
  213. * over the appearance of the site, which includes the markup returned from HTTP
  214. * requests and the CSS files used to style that markup. In order to ensure that
  215. * a theme can completely customize the markup, module developers should avoid
  216. * directly writing HTML markup for pages, blocks, and other user-visible output
  217. * in their modules, and instead return structured "render arrays" (see
  218. * @ref arrays below). Doing this also increases usability, by ensuring that the
  219. * markup used for similar functionality on different areas of the site is the
  220. * same, which gives users fewer user interface patterns to learn.
  221. *
  222. * For further information on the Theme and Render APIs, see:
  223. * - https://www.drupal.org/docs/8/theming
  224. * - https://www.drupal.org/developing/api/8/render
  225. * - @link themeable Theme system overview @endlink.
  226. *
  227. * @section arrays Render arrays
  228. * The core structure of the Render API is the render array, which is a
  229. * hierarchical associative array containing data to be rendered and properties
  230. * describing how the data should be rendered. A render array that is returned
  231. * by a function to specify markup to be sent to the web browser or other
  232. * services will eventually be rendered by a call to drupal_render(), which will
  233. * recurse through the render array hierarchy if appropriate, making calls into
  234. * the theme system to do the actual rendering. If a function or method actually
  235. * needs to return rendered output rather than a render array, the best practice
  236. * would be to create a render array, render it by calling drupal_render(), and
  237. * return that result, rather than writing the markup directly. See the
  238. * documentation of drupal_render() for more details of the rendering process.
  239. *
  240. * Each level in the hierarchy of a render array (including the outermost array)
  241. * has one or more array elements. Array elements whose names start with '#' are
  242. * known as "properties", and the array elements with other names are "children"
  243. * (constituting the next level of the hierarchy); the names of children are
  244. * flexible, while property names are specific to the Render API and the
  245. * particular type of data being rendered. A special case of render arrays is a
  246. * form array, which specifies the form elements for an HTML form; see the
  247. * @link form_api Form generation topic @endlink for more information on forms.
  248. *
  249. * Render arrays (at any level of the hierarchy) will usually have one of the
  250. * following properties defined:
  251. * - #type: Specifies that the array contains data and options for a particular
  252. * type of "render element" (for example, 'form', for an HTML form;
  253. * 'textfield', 'submit', for HTML form element types; 'table', for a table
  254. * with rows, columns, and headers). See @ref elements below for more on
  255. * render element types.
  256. * - #theme: Specifies that the array contains data to be themed by a particular
  257. * theme hook. Modules define theme hooks by implementing hook_theme(), which
  258. * specifies the input "variables" used to provide data and options; if a
  259. * hook_theme() implementation specifies variable 'foo', then in a render
  260. * array, you would provide this data using property '#foo'. Modules
  261. * implementing hook_theme() also need to provide a default implementation for
  262. * each of their theme hooks, normally in a Twig file. For more information
  263. * and to discover available theme hooks, see the documentation of
  264. * hook_theme() and the
  265. * @link themeable Default theme implementations topic. @endlink
  266. * - #markup: Specifies that the array provides HTML markup directly. Unless
  267. * the markup is very simple, such as an explanation in a paragraph tag, it
  268. * is normally preferable to use #theme or #type instead, so that the theme
  269. * can customize the markup. Note that the value is passed through
  270. * \Drupal\Component\Utility\Xss::filterAdmin(), which strips known XSS
  271. * vectors while allowing a permissive list of HTML tags that are not XSS
  272. * vectors. (For example, <script> and <style> are not allowed.) See
  273. * \Drupal\Component\Utility\Xss::$adminTags for the list of allowed tags. If
  274. * your markup needs any of the tags not in this list, then you can implement
  275. * a theme hook and/or an asset library. Alternatively, you can use the key
  276. * #allowed_tags to alter which tags are filtered.
  277. * - #plain_text: Specifies that the array provides text that needs to be
  278. * escaped. This value takes precedence over #markup.
  279. * - #allowed_tags: If #markup is supplied, this can be used to change which
  280. * tags are allowed in the markup. The value is an array of tags that
  281. * Xss::filter() would accept. If #plain_text is set, this value is ignored.
  282. *
  283. * Usage example:
  284. * @code
  285. * $output['admin_filtered_string'] = [
  286. * '#markup' => '<em>This is filtered using the admin tag list</em>',
  287. * ];
  288. * $output['filtered_string'] = [
  289. * '#markup' => '<video><source src="v.webm" type="video/webm"></video>',
  290. * '#allowed_tags' => ['video', 'source'],
  291. * ];
  292. * $output['escaped_string'] = [
  293. * '#plain_text' => '<em>This is escaped</em>',
  294. * ];
  295. * @endcode
  296. *
  297. * @see core.libraries.yml
  298. * @see hook_theme()
  299. *
  300. * JavaScript and CSS assets are specified in the render array using the
  301. * #attached property (see @ref sec_attached).
  302. *
  303. * @section elements Render elements
  304. * Render elements are defined by Drupal core and modules. The primary way to
  305. * define a render element is to create a render element plugin. There are
  306. * two types of render element plugins:
  307. * - Generic elements: Generic render element plugins implement
  308. * \Drupal\Core\Render\Element\ElementInterface, are annotated with
  309. * \Drupal\Core\Render\Annotation\RenderElement annotation, go in plugin
  310. * namespace Element, and generally extend the
  311. * \Drupal\Core\Render\Element\RenderElement base class.
  312. * - Form input elements: Render elements representing form input elements
  313. * implement \Drupal\Core\Render\Element\FormElementInterface, are annotated
  314. * with \Drupal\Core\Render\Annotation\FormElement annotation, go in plugin
  315. * namespace Element, and generally extend the
  316. * \Drupal\Core\Render\Element\FormElement base class.
  317. * See the @link plugin_api Plugin API topic @endlink for general information
  318. * on plugins. You can search for classes with the RenderElement or FormElement
  319. * annotation to discover what render elements are available. API reference
  320. * sites (such as https://api.drupal.org) generate lists of all existing
  321. * elements from these classes. Look for the Elements link in the API Navigation
  322. * block.
  323. *
  324. * Modules can define render elements by defining an element plugin.
  325. *
  326. * @section sec_caching Caching
  327. * The Drupal rendering process has the ability to cache rendered output at any
  328. * level in a render array hierarchy. This allows expensive calculations to be
  329. * done infrequently, and speeds up page loading. See the
  330. * @link cache Cache API topic @endlink for general information about the cache
  331. * system.
  332. *
  333. * In order to make caching possible, the following information needs to be
  334. * present:
  335. * - Cache keys: Identifiers for cacheable portions of render arrays. These
  336. * should be created and added for portions of a render array that
  337. * involve expensive calculations in the rendering process.
  338. * - Cache contexts: Contexts that may affect rendering, such as user role and
  339. * language. When no context is specified, it means that the render array
  340. * does not vary by any context.
  341. * - Cache tags: Tags for data that rendering depends on, such as for
  342. * individual nodes or user accounts, so that when these change the cache
  343. * can be automatically invalidated. If the data consists of entities, you
  344. * can use \Drupal\Core\Entity\EntityInterface::getCacheTags() to generate
  345. * appropriate tags; configuration objects have a similar method.
  346. * - Cache max-age: The maximum duration for which a render array may be cached.
  347. * Defaults to \Drupal\Core\Cache\Cache::PERMANENT (permanently cacheable).
  348. *
  349. * Cache information is provided in the #cache property in a render array. In
  350. * this property, always supply the cache contexts, tags, and max-age if a
  351. * render array varies by context, depends on some modifiable data, or depends
  352. * on information that's only valid for a limited time, respectively. Cache keys
  353. * should only be set on the portions of a render array that should be cached.
  354. * Contexts are automatically replaced with the value for the current request
  355. * (e.g. the current language) and combined with the keys to form a cache ID.
  356. * The cache contexts, tags, and max-age will be propagated up the render array
  357. * hierarchy to determine cacheability for containing render array sections.
  358. *
  359. * Here's an example of what a #cache property might contain:
  360. * @code
  361. * '#cache' => [
  362. * 'keys' => ['entity_view', 'node', $node->id()],
  363. * 'contexts' => ['languages'],
  364. * 'tags' => $node->getCacheTags(),
  365. * 'max-age' => Cache::PERMANENT,
  366. * ],
  367. * @endcode
  368. *
  369. * At the response level, you'll see X-Drupal-Cache-Contexts and
  370. * X-Drupal-Cache-Tags headers.
  371. *
  372. * See https://www.drupal.org/developing/api/8/render/arrays/cacheability for
  373. * details.
  374. *
  375. * @section sec_attached Attaching libraries in render arrays
  376. * Libraries, JavaScript settings, feeds, HTML <head> tags and HTML <head> links
  377. * are attached to elements using the #attached property. The #attached property
  378. * is an associative array, where the keys are the attachment types and the
  379. * values are the attached data.
  380. *
  381. * The #attached property can also be used to specify HTTP headers and the
  382. * response status code.
  383. *
  384. * The #attached property allows loading of asset libraries (which may contain
  385. * CSS assets, JavaScript assets, and JavaScript setting assets), JavaScript
  386. * settings, feeds, HTML <head> tags and HTML <head> links. Specify an array of
  387. * type => value pairs, where the type (most often 'library' — for libraries, or
  388. * 'drupalSettings' — for JavaScript settings) to attach these response-level
  389. * values. Example:
  390. * @code
  391. * $build['#attached']['library'][] = 'core/jquery';
  392. * $build['#attached']['drupalSettings']['foo'] = 'bar';
  393. * $build['#attached']['feed'][] = [$url, $this->t('Feed title')];
  394. * @endcode
  395. *
  396. * See \Drupal\Core\Render\AttachmentsResponseProcessorInterface for additional
  397. * information.
  398. *
  399. * See \Drupal\Core\Asset\LibraryDiscoveryParser::parseLibraryInfo() for more
  400. * information on how to define libraries.
  401. *
  402. * @section sec_placeholders Placeholders in render arrays
  403. * Render arrays have a placeholder mechanism, which can be used to add data
  404. * into the render array late in the rendering process. This works in a similar
  405. * manner to \Drupal\Component\Render\FormattableMarkup::placeholderFormat(),
  406. * with the text that ends up in the #markup property of the element at the
  407. * end of the rendering process getting substitutions from placeholders that
  408. * are stored in the 'placeholders' element of the #attached property.
  409. *
  410. * For example, after the rest of the rendering process was done, if your
  411. * render array contained:
  412. * @code
  413. * $build['my_element'] = [
  414. * '#markup' => 'Something about @foo',
  415. * '#attached' => [
  416. * 'placeholders' => [
  417. * '@foo' => ['#markup' => 'replacement'],
  418. * ],
  419. * ];
  420. * @endcode
  421. * then #markup would end up containing 'Something about replacement'.
  422. *
  423. * Note that each placeholder value *must* itself be a render array. It will be
  424. * rendered, and any cache tags generated during rendering will be added to the
  425. * cache tags for the markup.
  426. *
  427. * @section render_pipeline The render pipeline
  428. * The term "render pipeline" refers to the process Drupal uses to take
  429. * information provided by modules and render it into a response. See
  430. * https://www.drupal.org/developing/api/8/render for more details on this
  431. * process. For background on routing concepts, see
  432. * @link routing Routing API. @endlink
  433. *
  434. * There are in fact multiple render pipelines:
  435. * - Drupal always uses the Symfony render pipeline. See
  436. * https://symfony.com/doc/3.4/components/http_kernel.html
  437. * - Within the Symfony render pipeline, there is a Drupal render pipeline,
  438. * which handles controllers that return render arrays. (Symfony's render
  439. * pipeline only knows how to deal with Response objects; this pipeline
  440. * converts render arrays into Response objects.) These render arrays are
  441. * considered the main content, and can be rendered into multiple formats:
  442. * HTML, Ajax, dialog, and modal. Modules can add support for more formats, by
  443. * implementing a main content renderer, which is a service tagged with
  444. * 'render.main_content_renderer'.
  445. * - Finally, within the HTML main content renderer, there is another pipeline,
  446. * to allow for rendering the page containing the main content in multiple
  447. * ways: no decoration at all (just a page showing the main content) or blocks
  448. * (a page with regions, with blocks positioned in regions around the main
  449. * content). Modules can provide additional options, by implementing a page
  450. * variant, which is a plugin annotated with
  451. * \Drupal\Core\Display\Annotation\PageDisplayVariant.
  452. *
  453. * Routes whose controllers return a \Symfony\Component\HttpFoundation\Response
  454. * object are fully handled by the Symfony render pipeline.
  455. *
  456. * Routes whose controllers return the "main content" as a render array can be
  457. * requested in multiple formats (HTML, JSON, etc.) and/or in a "decorated"
  458. * manner, as described above.
  459. *
  460. * @see themeable
  461. * @see \Symfony\Component\HttpKernel\KernelEvents::VIEW
  462. * @see \Drupal\Core\EventSubscriber\MainContentViewSubscriber
  463. * @see \Drupal\Core\Render\MainContent\MainContentRendererInterface
  464. * @see \Drupal\Core\Render\MainContent\HtmlRenderer
  465. * @see \Drupal\Core\Render\RenderEvents::SELECT_PAGE_DISPLAY_VARIANT
  466. * @see \Drupal\Core\Render\Plugin\DisplayVariant\SimplePageVariant
  467. * @see \Drupal\block\Plugin\DisplayVariant\BlockPageVariant
  468. * @see \Drupal\Core\Render\BareHtmlPageRenderer
  469. *
  470. * @}
  471. */
  472. /**
  473. * @defgroup listing_page_element Page header for Elements page
  474. * @{
  475. * Introduction to form and render elements
  476. *
  477. * Render elements are referenced in render arrays. Render arrays contain data
  478. * to be rendered, along with meta-data and attributes that specify how to
  479. * render the data into markup; see the
  480. * @link theme_render Render API topic @endlink for an overview of render
  481. * arrays and render elements. Form arrays are a subset of render arrays,
  482. * representing HTML forms; form elements are a subset of render elements,
  483. * representing HTML elements for forms. See the
  484. * @link form_api Form API topic @endlink for an overview of forms, form
  485. * processing, and form arrays.
  486. *
  487. * Each form and render element type corresponds to an element plugin class;
  488. * each of them either extends \Drupal\Core\Render\Element\RenderElement
  489. * (render elements) or \Drupal\Core\Render\Element\FormElement (form
  490. * elements). Usage and properties are documented on the individual classes,
  491. * and the two base classes list common properties shared by all render
  492. * elements and the form element subset, respectively.
  493. *
  494. * @see theme_render
  495. * @see form_api
  496. * @see \Drupal\Core\Render\Element\RenderElement
  497. * @see \Drupal\Core\Render\Element\FormElement
  498. *
  499. * @}
  500. */
  501. /**
  502. * @addtogroup hooks
  503. * @{
  504. */
  505. /**
  506. * Allow themes to alter the theme-specific settings form.
  507. *
  508. * With this hook, themes can alter the theme-specific settings form in any way
  509. * allowable by Drupal's Form API, such as adding form elements, changing
  510. * default values and removing form elements. See the Form API documentation on
  511. * api.drupal.org for detailed information.
  512. *
  513. * Note that the base theme's form alterations will be run before any sub-theme
  514. * alterations.
  515. *
  516. * @param $form
  517. * Nested array of form elements that comprise the form.
  518. * @param $form_state
  519. * The current state of the form.
  520. */
  521. function hook_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  522. // Add a checkbox to toggle the breadcrumb trail.
  523. $form['toggle_breadcrumb'] = [
  524. '#type' => 'checkbox',
  525. '#title' => t('Display the breadcrumb'),
  526. '#default_value' => theme_get_setting('features.breadcrumb'),
  527. '#description' => t('Show a trail of links from the homepage to the current page.'),
  528. ];
  529. }
  530. /**
  531. * Preprocess theme variables for templates.
  532. *
  533. * This hook allows modules to preprocess theme variables for theme templates.
  534. * It is called for all theme hooks implemented as templates, but not for theme
  535. * hooks implemented as functions. hook_preprocess_HOOK() can be used to
  536. * preprocess variables for a specific theme hook, whether implemented as a
  537. * template or function.
  538. *
  539. * For more detailed information, see the
  540. * @link themeable Theme system overview topic @endlink.
  541. *
  542. * @param $variables
  543. * The variables array (modify in place).
  544. * @param $hook
  545. * The name of the theme hook.
  546. */
  547. function hook_preprocess(&$variables, $hook) {
  548. static $hooks;
  549. // Add contextual links to the variables, if the user has permission.
  550. if (!\Drupal::currentUser()->hasPermission('access contextual links')) {
  551. return;
  552. }
  553. if (!isset($hooks)) {
  554. $hooks = theme_get_registry();
  555. }
  556. // Determine the primary theme function argument.
  557. if (isset($hooks[$hook]['variables'])) {
  558. $keys = array_keys($hooks[$hook]['variables']);
  559. $key = $keys[0];
  560. }
  561. else {
  562. $key = $hooks[$hook]['render element'];
  563. }
  564. if (isset($variables[$key])) {
  565. $element = $variables[$key];
  566. }
  567. if (isset($element) && is_array($element) && !empty($element['#contextual_links'])) {
  568. $variables['title_suffix']['contextual_links'] = contextual_links_view($element);
  569. if (!empty($variables['title_suffix']['contextual_links'])) {
  570. $variables['attributes']['class'][] = 'contextual-links-region';
  571. }
  572. }
  573. }
  574. /**
  575. * Preprocess theme variables for a specific theme hook.
  576. *
  577. * This hook allows modules to preprocess theme variables for a specific theme
  578. * hook. It should only be used if a module needs to override or add to the
  579. * theme preprocessing for a theme hook it didn't define.
  580. *
  581. * For more detailed information, see the
  582. * @link themeable Theme system overview topic @endlink.
  583. *
  584. * @param $variables
  585. * The variables array (modify in place).
  586. */
  587. function hook_preprocess_HOOK(&$variables) {
  588. // This example is from rdf_preprocess_image(). It adds an RDF attribute
  589. // to the image hook's variables.
  590. $variables['attributes']['typeof'] = ['foaf:Image'];
  591. }
  592. /**
  593. * Provides alternate named suggestions for a specific theme hook.
  594. *
  595. * This hook allows modules to provide alternative theme function or template
  596. * name suggestions.
  597. *
  598. * HOOK is the least-specific version of the hook being called. For example, if
  599. * '#theme' => 'node__article' is called, then hook_theme_suggestions_node()
  600. * will be invoked, not hook_theme_suggestions_node__article(). The specific
  601. * hook called (in this case 'node__article') is available in
  602. * $variables['theme_hook_original'].
  603. *
  604. * Implementations of this hook must be placed in *.module or *.theme files, or
  605. * must otherwise make sure that the hook implementation is available at
  606. * any given time.
  607. *
  608. * @todo Add @code sample.
  609. *
  610. * @param array $variables
  611. * An array of variables passed to the theme hook. Note that this hook is
  612. * invoked before any preprocessing.
  613. *
  614. * @return array
  615. * An array of theme suggestions.
  616. *
  617. * @see hook_theme_suggestions_HOOK_alter()
  618. */
  619. function hook_theme_suggestions_HOOK(array $variables) {
  620. $suggestions = [];
  621. $suggestions[] = 'hookname__' . $variables['elements']['#langcode'];
  622. return $suggestions;
  623. }
  624. /**
  625. * Alters named suggestions for all theme hooks.
  626. *
  627. * This hook is invoked for all theme hooks, if you are targeting a specific
  628. * theme hook it's best to use hook_theme_suggestions_HOOK_alter().
  629. *
  630. * The call order is as follows: all existing suggestion alter functions are
  631. * called for module A, then all for module B, etc., followed by all for any
  632. * base theme(s), and finally for the active theme. The order is
  633. * determined by system weight, then by extension (module or theme) name.
  634. *
  635. * Within each module or theme, suggestion alter hooks are called in the
  636. * following order: first, hook_theme_suggestions_alter(); second,
  637. * hook_theme_suggestions_HOOK_alter(). So, for each module or theme, the more
  638. * general hooks are called first followed by the more specific.
  639. *
  640. * In the following example, we provide an alternative template suggestion to
  641. * node and taxonomy term templates based on the user being logged in.
  642. * @code
  643. * function MYMODULE_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  644. * if (\Drupal::currentUser()->isAuthenticated() && in_array($hook, array('node', 'taxonomy_term'))) {
  645. * $suggestions[] = $hook . '__' . 'logged_in';
  646. * }
  647. * }
  648. *
  649. * @endcode
  650. *
  651. * @param array $suggestions
  652. * An array of alternate, more specific names for template files or theme
  653. * functions.
  654. * @param array $variables
  655. * An array of variables passed to the theme hook. Note that this hook is
  656. * invoked before any variable preprocessing.
  657. * @param string $hook
  658. * The base hook name. For example, if '#theme' => 'node__article' is called,
  659. * then $hook will be 'node', not 'node__article'. The specific hook called
  660. * (in this case 'node__article') is available in
  661. * $variables['theme_hook_original'].
  662. *
  663. * @return array
  664. * An array of theme suggestions.
  665. *
  666. * @see hook_theme_suggestions_HOOK_alter()
  667. */
  668. function hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  669. // Add an interface-language specific suggestion to all theme hooks.
  670. $suggestions[] = $hook . '__' . \Drupal::languageManager()->getCurrentLanguage()->getId();
  671. }
  672. /**
  673. * Alters named suggestions for a specific theme hook.
  674. *
  675. * This hook allows any module or theme to provide alternative theme function or
  676. * template name suggestions and reorder or remove suggestions provided by
  677. * hook_theme_suggestions_HOOK() or by earlier invocations of this hook.
  678. *
  679. * HOOK is the least-specific version of the hook being called. For example, if
  680. * '#theme' => 'node__article' is called, then node_theme_suggestions_node()
  681. * will be invoked, not node_theme_suggestions_node__article(). The specific
  682. * hook called (in this case 'node__article') is available in
  683. * $variables['theme_hook_original'].
  684. *
  685. * Implementations of this hook must be placed in *.module or *.theme files, or
  686. * must otherwise make sure that the hook implementation is available at
  687. * any given time.
  688. *
  689. * @todo Add @code sample.
  690. *
  691. * @param array $suggestions
  692. * An array of theme suggestions.
  693. * @param array $variables
  694. * An array of variables passed to the theme hook. Note that this hook is
  695. * invoked before any preprocessing.
  696. *
  697. * @see hook_theme_suggestions_alter()
  698. * @see hook_theme_suggestions_HOOK()
  699. */
  700. function hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables) {
  701. if (empty($variables['header'])) {
  702. $suggestions[] = 'hookname__no_header';
  703. }
  704. }
  705. /**
  706. * Respond to themes being installed.
  707. *
  708. * @param array $theme_list
  709. * Array containing the names of the themes being installed.
  710. *
  711. * @see \Drupal\Core\Extension\ThemeInstallerInterface::install()
  712. */
  713. function hook_themes_installed($theme_list) {
  714. foreach ($theme_list as $theme) {
  715. block_theme_initialize($theme);
  716. }
  717. }
  718. /**
  719. * Respond to themes being uninstalled.
  720. *
  721. * @param array $themes
  722. * Array containing the names of the themes being uninstalled.
  723. *
  724. * @see \Drupal\Core\Extension\ThemeInstallerInterface::uninstall()
  725. */
  726. function hook_themes_uninstalled(array $themes) {
  727. // Remove some state entries depending on the theme.
  728. foreach ($themes as $theme) {
  729. \Drupal::state()->delete('example.' . $theme);
  730. }
  731. }
  732. /**
  733. * Declare a template file extension to be used with a theme engine.
  734. *
  735. * This hook is used in a theme engine implementation in the format of
  736. * ENGINE_extension().
  737. *
  738. * @return string
  739. * The file extension the theme engine will recognize.
  740. */
  741. function hook_extension() {
  742. // Extension for template base names in Twig.
  743. return '.html.twig';
  744. }
  745. /**
  746. * Render a template using the theme engine.
  747. *
  748. * It is the theme engine's responsibility to escape variables. The only
  749. * exception is if a variable implements
  750. * \Drupal\Component\Render\MarkupInterface. Drupal is inherently unsafe if
  751. * other variables are not escaped. The helper function
  752. * theme_render_and_autoescape() may be used for this.
  753. *
  754. * @param string $template_file
  755. * The path (relative to the Drupal root directory) to the template to be
  756. * rendered including its extension in the format 'path/to/TEMPLATE_NAME.EXT'.
  757. * @param array $variables
  758. * A keyed array of variables that are available for composing the output. The
  759. * theme engine is responsible for passing all the variables to the template.
  760. * Depending on the code in the template, all or just a subset of the
  761. * variables might be used in the template.
  762. *
  763. * @return string
  764. * The output generated from the template. In most cases this will be a string
  765. * containing HTML markup.
  766. */
  767. function hook_render_template($template_file, $variables) {
  768. $twig_service = \Drupal::service('twig');
  769. return $twig_service->loadTemplate($template_file)->render($variables);
  770. }
  771. /**
  772. * Alter the element type information returned from modules.
  773. *
  774. * A module may implement this hook in order to alter the element type defaults
  775. * defined by a module.
  776. *
  777. * @param array $info
  778. * An associative array with structure identical to that of the return value
  779. * of \Drupal\Core\Render\ElementInfoManagerInterface::getInfo().
  780. *
  781. * @see \Drupal\Core\Render\ElementInfoManager
  782. * @see \Drupal\Core\Render\Element\ElementInterface
  783. */
  784. function hook_element_info_alter(array &$info) {
  785. // Decrease the default size of textfields.
  786. if (isset($info['textfield']['#size'])) {
  787. $info['textfield']['#size'] = 40;
  788. }
  789. }
  790. /**
  791. * Alter Element plugin definitions.
  792. *
  793. * Whenever possible, hook_element_info_alter() should be used to alter the
  794. * default properties of an element type. Use this hook only when the plugin
  795. * definition itself needs to be altered.
  796. *
  797. * @param array $definitions
  798. * An array of Element plugin definitions.
  799. *
  800. * @see \Drupal\Core\Render\ElementInfoManager
  801. * @see \Drupal\Core\Render\Element\ElementInterface
  802. */
  803. function hook_element_plugin_alter(array &$definitions) {
  804. // Use a custom class for the LayoutBuilder element.
  805. $definitions['layout_builder']['class'] = '\Drupal\mymodule\Element\MyLayoutBuilderElement';
  806. }
  807. /**
  808. * Perform necessary alterations to the JavaScript before it is presented on
  809. * the page.
  810. *
  811. * @param $javascript
  812. * An array of all JavaScript being presented on the page.
  813. * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets
  814. * The assets attached to the current response.
  815. *
  816. * @see drupal_js_defaults()
  817. * @see \Drupal\Core\Asset\AssetResolver
  818. */
  819. function hook_js_alter(&$javascript, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  820. // Swap out jQuery to use an updated version of the library.
  821. $javascript['core/assets/vendor/jquery/jquery.min.js']['data'] = drupal_get_path('module', 'jquery_update') . '/jquery.js';
  822. }
  823. /**
  824. * Add dynamic library definitions.
  825. *
  826. * Modules may implement this hook to add dynamic library definitions. Static
  827. * libraries, which do not depend on any runtime information, should be declared
  828. * in a modulename.libraries.yml file instead.
  829. *
  830. * @return array[]
  831. * An array of library definitions to register, keyed by library ID. The
  832. * library ID will be prefixed with the module name automatically.
  833. *
  834. * @see core.libraries.yml
  835. * @see hook_library_info_alter()
  836. */
  837. function hook_library_info_build() {
  838. $libraries = [];
  839. // Add a library whose information changes depending on certain conditions.
  840. $libraries['mymodule.zombie'] = [
  841. 'dependencies' => [
  842. 'core/backbone',
  843. ],
  844. ];
  845. if (Drupal::moduleHandler()->moduleExists('minifyzombies')) {
  846. $libraries['mymodule.zombie'] += [
  847. 'js' => [
  848. 'mymodule.zombie.min.js' => [],
  849. ],
  850. 'css' => [
  851. 'base' => [
  852. 'mymodule.zombie.min.css' => [],
  853. ],
  854. ],
  855. ];
  856. }
  857. else {
  858. $libraries['mymodule.zombie'] += [
  859. 'js' => [
  860. 'mymodule.zombie.js' => [],
  861. ],
  862. 'css' => [
  863. 'base' => [
  864. 'mymodule.zombie.css' => [],
  865. ],
  866. ],
  867. ];
  868. }
  869. // Add a library only if a certain condition is met. If code wants to
  870. // integrate with this library it is safe to (try to) load it unconditionally
  871. // without reproducing this check. If the library definition does not exist
  872. // the library (of course) not be loaded but no notices or errors will be
  873. // triggered.
  874. if (Drupal::moduleHandler()->moduleExists('vampirize')) {
  875. $libraries['mymodule.vampire'] = [
  876. 'js' => [
  877. 'js/vampire.js' => [],
  878. ],
  879. 'css' => [
  880. 'base' => [
  881. 'css/vampire.css',
  882. ],
  883. ],
  884. 'dependencies' => [
  885. 'core/jquery',
  886. ],
  887. ];
  888. }
  889. return $libraries;
  890. }
  891. /**
  892. * Modify the JavaScript settings (drupalSettings).
  893. *
  894. * @param array &$settings
  895. * An array of all JavaScript settings (drupalSettings) being presented on the
  896. * page.
  897. * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets
  898. * The assets attached to the current response.
  899. *
  900. * @see \Drupal\Core\Asset\AssetResolver
  901. *
  902. * The results of this hook are cached, however modules may use
  903. * hook_js_settings_alter() to dynamically alter settings.
  904. */
  905. function hook_js_settings_build(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  906. // Manipulate settings.
  907. if (isset($settings['dialog'])) {
  908. $settings['dialog']['autoResize'] = FALSE;
  909. }
  910. }
  911. /**
  912. * Perform necessary alterations to the JavaScript settings (drupalSettings).
  913. *
  914. * @param array &$settings
  915. * An array of all JavaScript settings (drupalSettings) being presented on the
  916. * page.
  917. * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets
  918. * The assets attached to the current response.
  919. *
  920. * @see \Drupal\Core\Asset\AssetResolver
  921. */
  922. function hook_js_settings_alter(array &$settings, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  923. // Add settings.
  924. $settings['user']['uid'] = \Drupal::currentUser();
  925. // Manipulate settings.
  926. if (isset($settings['dialog'])) {
  927. $settings['dialog']['autoResize'] = FALSE;
  928. }
  929. }
  930. /**
  931. * Alter libraries provided by an extension.
  932. *
  933. * Allows modules and themes to change libraries' definitions; mostly used to
  934. * update a library to a newer version, while ensuring backward compatibility.
  935. * In general, such manipulations should only be done to extend the library's
  936. * functionality in a backward-compatible way, to avoid breaking other modules
  937. * and themes that may be using the library.
  938. *
  939. * @param array $libraries
  940. * An associative array of libraries registered by $extension. Keyed by
  941. * internal library name and passed by reference.
  942. * @param string $extension
  943. * Can either be 'core' or the machine name of the extension that registered
  944. * the libraries.
  945. *
  946. * @see \Drupal\Core\Asset\LibraryDiscoveryParser::parseLibraryInfo()
  947. */
  948. function hook_library_info_alter(&$libraries, $extension) {
  949. // Update Farbtastic to version 2.0.
  950. if ($extension == 'core' && isset($libraries['jquery.farbtastic'])) {
  951. // Verify existing version is older than the one we are updating to.
  952. if (version_compare($libraries['jquery.farbtastic']['version'], '2.0', '<')) {
  953. // Update the existing Farbtastic to version 2.0.
  954. $libraries['jquery.farbtastic']['version'] = '2.0';
  955. // To accurately replace library files, the order of files and the options
  956. // of each file have to be retained; e.g., like this:
  957. $old_path = 'assets/vendor/farbtastic';
  958. // Since the replaced library files are no longer located in a directory
  959. // relative to the original extension, specify an absolute path (relative
  960. // to DRUPAL_ROOT / base_path()) to the new location.
  961. $new_path = '/' . drupal_get_path('module', 'farbtastic_update') . '/js';
  962. $new_js = [];
  963. $replacements = [
  964. $old_path . '/farbtastic.js' => $new_path . '/farbtastic-2.0.js',
  965. ];
  966. foreach ($libraries['jquery.farbtastic']['js'] as $source => $options) {
  967. if (isset($replacements[$source])) {
  968. $new_js[$replacements[$source]] = $options;
  969. }
  970. else {
  971. $new_js[$source] = $options;
  972. }
  973. }
  974. $libraries['jquery.farbtastic']['js'] = $new_js;
  975. }
  976. }
  977. }
  978. /**
  979. * Alter CSS files before they are output on the page.
  980. *
  981. * @param $css
  982. * An array of all CSS items (files and inline CSS) being requested on the page.
  983. * @param \Drupal\Core\Asset\AttachedAssetsInterface $assets
  984. * The assets attached to the current response.
  985. *
  986. * @see Drupal\Core\Asset\LibraryResolverInterface::getCssAssets()
  987. */
  988. function hook_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
  989. // Remove defaults.css file.
  990. unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
  991. }
  992. /**
  993. * Add attachments (typically assets) to a page before it is rendered.
  994. *
  995. * Use this hook when you want to conditionally add attachments to a page.
  996. *
  997. * If you want to alter the attachments added by other modules or if your module
  998. * depends on the elements of other modules, use hook_page_attachments_alter()
  999. * instead, which runs after this hook.
  1000. *
  1001. * If you try to add anything but #attached and #cache to the array, an
  1002. * exception is thrown.
  1003. *
  1004. * @param array &$attachments
  1005. * An array that you can add attachments to.
  1006. *
  1007. * @see hook_page_attachments_alter()
  1008. */
  1009. function hook_page_attachments(array &$attachments) {
  1010. // Unconditionally attach an asset to the page.
  1011. $attachments['#attached']['library'][] = 'core/drupalSettings';
  1012. // Conditionally attach an asset to the page.
  1013. if (!\Drupal::currentUser()->hasPermission('may pet kittens')) {
  1014. $attachments['#attached']['library'][] = 'core/jquery';
  1015. }
  1016. }
  1017. /**
  1018. * Alter attachments (typically assets) to a page before it is rendered.
  1019. *
  1020. * Use this hook when you want to remove or alter attachments on the page, or
  1021. * add attachments to the page that depend on another module's attachments (this
  1022. * hook runs after hook_page_attachments().
  1023. *
  1024. * If you try to add anything but #attached and #cache to the array, an
  1025. * exception is thrown.
  1026. *
  1027. * @param array &$attachments
  1028. * Array of all attachments provided by hook_page_attachments() implementations.
  1029. *
  1030. * @see hook_page_attachments()
  1031. */
  1032. function hook_page_attachments_alter(array &$attachments) {
  1033. // Conditionally remove an asset.
  1034. if (in_array('core/jquery', $attachments['#attached']['library'])) {
  1035. $index = array_search('core/jquery', $attachments['#attached']['library']);
  1036. unset($attachments['#attached']['library'][$index]);
  1037. }
  1038. }
  1039. /**
  1040. * Add a renderable array to the top of the page.
  1041. *
  1042. * @param array $page_top
  1043. * A renderable array representing the top of the page.
  1044. */
  1045. function hook_page_top(array &$page_top) {
  1046. $page_top['mymodule'] = ['#markup' => 'This is the top.'];
  1047. }
  1048. /**
  1049. * Add a renderable array to the bottom of the page.
  1050. *
  1051. * @param array $page_bottom
  1052. * A renderable array representing the bottom of the page.
  1053. */
  1054. function hook_page_bottom(array &$page_bottom) {
  1055. $page_bottom['mymodule'] = ['#markup' => 'This is the bottom.'];
  1056. }
  1057. /**
  1058. * Register a module or theme's theme implementations.
  1059. *
  1060. * The implementations declared by this hook specify how a particular render
  1061. * array is to be rendered as HTML.
  1062. *
  1063. * @param array $existing
  1064. * An array of existing implementations that may be used for override
  1065. * purposes. This is primarily useful for themes that may wish to examine
  1066. * existing implementations to extract data (such as arguments) so that
  1067. * it may properly register its own, higher priority implementations.
  1068. * @param $type
  1069. * Whether a theme, module, etc. is being processed. This is primarily useful
  1070. * so that themes tell if they are the actual theme being called or a parent
  1071. * theme. May be one of:
  1072. * - 'module': A module is being checked for theme implementations.
  1073. * - 'base_theme_engine': A theme engine is being checked for a theme that is
  1074. * a parent of the actual theme being used.
  1075. * - 'theme_engine': A theme engine is being checked for the actual theme
  1076. * being used.
  1077. * - 'base_theme': A base theme is being checked for theme implementations.
  1078. * - 'theme': The actual theme in use is being checked.
  1079. * @param $theme
  1080. * The actual name of theme, module, etc. that is being being processed.
  1081. * @param $path
  1082. * The directory path of the theme or module, so that it doesn't need to be
  1083. * looked up.
  1084. *
  1085. * @return array
  1086. * An associative array of information about theme implementations. The keys
  1087. * on the outer array are known as "theme hooks". For theme suggestions,
  1088. * instead of the array key being the base theme hook, the key is a theme
  1089. * suggestion name with the format 'base_hook_name__sub_hook_name'.
  1090. * For render elements, the key is the machine name of the render element.
  1091. * The array values are themselves arrays containing information about the
  1092. * theme hook and its implementation. Each information array must contain
  1093. * either a 'variables' element (for using a #theme element) or a
  1094. * 'render element' element (for render elements), but not both.
  1095. * The following elements may be part of each information array:
  1096. * - variables: Only used for #theme in render array: an array of variables,
  1097. * where the array keys are the names of the variables, and the array
  1098. * values are the default values if they are not given in the render array.
  1099. * Template implementations receive each array key as a variable in the
  1100. * template file (so they must be legal PHP/Twig variable names). Function
  1101. * implementations are passed the variables in a single $variables function
  1102. * argument. If you are using these variables in a render array, prefix the
  1103. * variable names defined here with a #.
  1104. * - render element: Used for render element items only: the name of the
  1105. * renderable element or element tree to pass to the theme function. This
  1106. * name is used as the name of the variable that holds the renderable
  1107. * element or tree in preprocess and process functions.
  1108. * - file: The file the implementation resides in. This file will be included
  1109. * prior to the theme being rendered, to make sure that the function or
  1110. * preprocess function (as needed) is actually loaded.
  1111. * - path: Override the path of the file to be used. Ordinarily the module or
  1112. * theme path will be used, but if the file will not be in the default
  1113. * path, include it here. This path should be relative to the Drupal root
  1114. * directory.
  1115. * - template: If specified, the theme implementation is a template file, and
  1116. * this is the template name. Do not add 'html.twig' on the end of the
  1117. * template name. The extension will be added automatically by the default
  1118. * rendering engine (which is Twig.) If 'path' is specified, 'template'
  1119. * should also be specified. If neither 'template' nor 'function' are
  1120. * specified, a default template name will be assumed. For example, if a
  1121. * module registers the 'search_result' theme hook, 'search-result' will be
  1122. * assigned as its template name.
  1123. * - function: (deprecated in Drupal 8.0.x, will be removed in Drupal 9.0.x)
  1124. * If specified, this will be the function name to invoke for this
  1125. * implementation. If neither 'template' nor 'function' are specified, a
  1126. * default template name will be assumed. See above for more details.
  1127. * - base hook: Used for theme suggestions only: the base theme hook name.
  1128. * Instead of this suggestion's implementation being used directly, the base
  1129. * hook will be invoked with this implementation as its first suggestion.
  1130. * The base hook's files will be included and the base hook's preprocess
  1131. * functions will be called in addition to any suggestion's preprocess
  1132. * functions. If an implementation of hook_theme_suggestions_HOOK() (where
  1133. * HOOK is the base hook) changes the suggestion order, a different
  1134. * suggestion may be used in place of this suggestion. If after
  1135. * hook_theme_suggestions_HOOK() this suggestion remains the first
  1136. * suggestion, then this suggestion's function or template will be used to
  1137. * generate the rendered output.
  1138. * - pattern: A regular expression pattern to be used to allow this theme
  1139. * implementation to have a dynamic name. The convention is to use __ to
  1140. * differentiate the dynamic portion of the theme. For example, to allow
  1141. * forums to be themed individually, the pattern might be: 'forum__'. Then,
  1142. * when the forum is rendered, following render array can be used:
  1143. * @code
  1144. * $render_array = array(
  1145. * '#theme' => array('forum__' . $tid, 'forum'),
  1146. * '#forum' => $forum,
  1147. * );
  1148. * @endcode
  1149. * - preprocess functions: A list of functions used to preprocess this data.
  1150. * Ordinarily this won't be used; it's automatically filled in. By default,
  1151. * for a module this will be filled in as template_preprocess_HOOK. For
  1152. * a theme this will be filled in as twig_preprocess and
  1153. * twig_preprocess_HOOK as well as themename_preprocess and
  1154. * themename_preprocess_HOOK.
  1155. * - override preprocess functions: Set to TRUE when a theme does NOT want
  1156. * the standard preprocess functions to run. This can be used to give a
  1157. * theme FULL control over how variables are set. For example, if a theme
  1158. * wants total control over how certain variables in the page.html.twig are
  1159. * set, this can be set to true. Please keep in mind that when this is used
  1160. * by a theme, that theme becomes responsible for making sure necessary
  1161. * variables are set.
  1162. * - type: (automatically derived) Where the theme hook is defined:
  1163. * 'module', 'theme_engine', or 'theme'.
  1164. * - theme path: (automatically derived) The directory path of the theme or
  1165. * module, so that it doesn't need to be looked up.
  1166. *
  1167. * @see themeable
  1168. * @see hook_theme_registry_alter()
  1169. */
  1170. function hook_theme($existing, $type, $theme, $path) {
  1171. return [
  1172. 'forum_display' => [
  1173. 'variables' => ['forums' => NULL, 'topics' => NULL, 'parents' => NULL, 'tid' => NULL, 'sortby' => NULL, 'forum_per_page' => NULL],
  1174. ],
  1175. 'forum_list' => [
  1176. 'variables' => ['forums' => NULL, 'parents' => NULL, 'tid' => NULL],
  1177. ],
  1178. 'forum_icon' => [
  1179. 'variables' => ['new_posts' => NULL, 'num_posts' => 0, 'comment_mode' => 0, 'sticky' => 0],
  1180. ],
  1181. 'status_report' => [
  1182. 'render element' => 'requirements',
  1183. 'file' => 'system.admin.inc',
  1184. ],
  1185. ];
  1186. }
  1187. /**
  1188. * Alter the theme registry information returned from hook_theme().
  1189. *
  1190. * The theme registry stores information about all available theme hooks,
  1191. * including which callback functions those hooks will call when triggered,
  1192. * what template files are exposed by these hooks, and so on.
  1193. *
  1194. * Note that this hook is only executed as the theme cache is re-built.
  1195. * Changes here will not be visible until the next cache clear.
  1196. *
  1197. * The $theme_registry array is keyed by theme hook name, and contains the
  1198. * information returned from hook_theme(), as well as additional properties
  1199. * added by \Drupal\Core\Theme\Registry::processExtension().
  1200. *
  1201. * For example:
  1202. * @code
  1203. * $theme_registry['block_content_add_list'] = array (
  1204. * 'template' => 'block-content-add-list',
  1205. * 'path' => 'core/themes/seven/templates',
  1206. * 'type' => 'theme_engine',
  1207. * 'theme path' => 'core/themes/seven',
  1208. * 'includes' => array (
  1209. * 0 => 'core/modules/block_content/block_content.pages.inc',
  1210. * ),
  1211. * 'variables' => array (
  1212. * 'content' => NULL,
  1213. * ),
  1214. * 'preprocess functions' => array (
  1215. * 0 => 'template_preprocess',
  1216. * 1 => 'template_preprocess_block_content_add_list',
  1217. * 2 => 'contextual_preprocess',
  1218. * 3 => 'seven_preprocess_block_content_add_list',
  1219. * ),
  1220. * );
  1221. * @endcode
  1222. *
  1223. * @param $theme_registry
  1224. * The entire cache of theme registry information, post-processing.
  1225. *
  1226. * @see hook_theme()
  1227. * @see \Drupal\Core\Theme\Registry::processExtension()
  1228. */
  1229. function hook_theme_registry_alter(&$theme_registry) {
  1230. // Kill the next/previous forum topic navigation links.
  1231. foreach ($theme_registry['forum_topic_navigation']['preprocess functions'] as $key => $value) {
  1232. if ($value == 'template_preprocess_forum_topic_navigation') {
  1233. unset($theme_registry['forum_topic_navigation']['preprocess functions'][$key]);
  1234. }
  1235. }
  1236. }
  1237. /**
  1238. * Alter the default, hook-independent variables for all templates.
  1239. *
  1240. * Allows modules to provide additional default template variables or manipulate
  1241. * existing. This hook is invoked from template_preprocess() after basic default
  1242. * template variables have been set up and before the next template preprocess
  1243. * function is invoked.
  1244. *
  1245. * Note that the default template variables are statically cached within a
  1246. * request. When adding a template variable that depends on other context, it is
  1247. * your responsibility to appropriately reset the static cache in
  1248. * template_preprocess() when needed:
  1249. * @code
  1250. * drupal_static_reset('template_preprocess');
  1251. * @endcode
  1252. *
  1253. * See user_template_preprocess_default_variables_alter() for an example.
  1254. *
  1255. * @param array $variables
  1256. * An associative array of default template variables, as set up by
  1257. * _template_preprocess_default_variables(). Passed by reference.
  1258. *
  1259. * @see template_preprocess()
  1260. * @see _template_preprocess_default_variables()
  1261. */
  1262. function hook_template_preprocess_default_variables_alter(&$variables) {
  1263. $variables['is_admin'] = \Drupal::currentUser()->hasPermission('access administration pages');
  1264. }
  1265. /**
  1266. * @} End of "addtogroup hooks".
  1267. */