Drupal theme api常用预处理函数(一)

hook_element_info_alter

修改元素的默认值
function hook_element_info_alter(array &$info) {
 // 判断元素textfield是否有size属性,有的话设置大小为40
 if (isset($info['textfield']['#size'])) {
   $info['textfield']['#size'] = 40;
 }
}
function hook_element_info_alter(array &$info) {
 // 判断元素是否是submit,为真添加自定义class
 if (isset($info['submit'])) {
   $info['submit']['#attributes']['class'] = 'btn btn-success';
 }
}

hook_form_system_theme_settings_alter

更改主题特定的设置表单

添加表单元素,更改默认值,删除表单元素

function hook_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
 // Add a checkbox to toggle the breadcrumb trail.
 $form['toggle_breadcrumb'] = [
   '#type' => 'checkbox',
   '#title' => t('Display the breadcrumb'),
   '#default_value' => theme_get_setting('features.breadcrumb'),
   '#description' => t('Show a trail of links from the homepage to the current page.'),
 ];
}

hook_theme_suggestions_HOOK

提供备用主题命名建议
function hook_theme_suggestions_HOOK(array $variables) {
 $suggestions = [];
 $suggestions[] = 'hookname__' . $variables['elements']['#langcode'];
 return $suggestions;
}

hook_theme_suggestions_HOOK_alter

主题钩子命名的建议

它会重新排序或删除由hook_theme_suggestions_HOOK提供的建议或先调用此钩子

function hook_theme_suggestions_HOOK_alter(array &$suggestions, array $variables) {
 if (empty($variables['header'])) {
   $suggestions[] = 'hookname__' . 'no_header';
 }
}

hook_theme_suggestions_alter

更改所有主题钩子命名建议
function MYMODULE_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
   // 根据登录的用户为节点和分类术语模板提供了替代模板建议
 if (\Drupal::currentUser()->isAuthenticated() && in_array($hook, array('node', 'taxonomy_term'))) {
   $suggestions[] = $hook . '__' . 'logged_in';
 }
}
function hook_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
 // Add an interface-language specific suggestion to all theme hooks.
 $suggestions[] = $hook . '__' . \Drupal::languageManager()->getCurrentLanguage()->getId();
}

hook_css_alter

更改css文件
function hook_css_alter(&$css, \Drupal\Core\Asset\AttachedAssetsInterface $assets) {
 // Remove defaults.css file.
 unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
}

hook_page_attachments

将资源库添加到页面中
function hook_page_attachments(array &$attachments) {
 // Unconditionally attach an asset to the page.
 $attachments['#attached']['library'][] = 'core/domready';

 // Conditionally attach an asset to the page.
 if (!\Drupal::currentUser()->hasPermission('may pet kittens')) {
   $attachments['#attached']['library'][] = 'core/jquery';
 }
}

hook_page_attachments_alter

删除或者更改页面的资源库,或者将附件添加到依赖于另一个模块附件的页面上

此钩子在hook_page_attachments()之后运行

function hook_page_attachments_alter(array &$attachments) {
 // Conditionally remove an asset.
 if (in_array('core/jquery', $attachments['#attached']['library'])) {
   $index = array_search('core/jquery', $attachments['#attached']['library']);
   unset($attachments['#attached']['library'][$index]);
 }
}