9.4 高级渲染数组模式

HTML 属性

龷龶龳龯龮龭龬龩龧龦 HTML 龙龖龔龑龐 ID 龉 Class齽齹齸齶龙龖齳齯齫齨齦 Twig 齛齘齕齔齐齎 themer 鼾鼺龉鼹鼵齸齶鼳齹鼰鼯鼬齸鼨齕鼤龮龭龬龩鼾鼺 #attributes 鼙鼗齹龬龩鼔鼒鼐龙龖齕鼳鼐龙龖鼔鼳齹

$element = [
  '#type' => 'my_element',
  '#config_one' => 'blue',
];

$element['#attributes'] = [
  'id' => 'my_blue_element_1',
  'class' => ['my-element','blue'],
];

齸齐齎鼍鼉鼈鼄鼂鼀鼔黼黺黷黴黱黮黪黨黥鼹鼵 —– $variables[‘attributes’] 齯 theme.inc 鼈鼔 template_process() 麶龬麳麰齕template_process() 麬黥麨麤麡鼔龮龭龬龩齹$variables[‘attributes’] 鼐麞鼨麚麘齕麖麓鼳麒麑麏 $variables[‘element’][‘#attributes’] 鼈齕麎齸鼨麖麓鼳麌麘麋麈麇麃齹

function hook_preprocess_my_element(&$variables) {
  $variables['attributes']['id'] = 'my_blue_element_altered_id';
}

麂麀龷鹽鹼麏 Twig 齛齘鼀鹸麃齸齶鼳鹴龔鹰鼍鼉鼈鼄鼂齽

麏黼黺黷麶龬鹭麃麨 attributes 鼙鼗麂麀齕鹫鹧齯鹦鼙鼰黮鹢齕鹼鹠鹞鹠麏 Twig 鼀鹛鹙龉鹘鹖齹齸鼨黺黷鹕 ThemeManager.php 鼀鼔 render() 鹎鹌齹

<div {{ attributes }}>
{{ element }}
</div>

包装器(#theme_wrapper)和容器

龷龶麃 div 鹋鹉龷鼔鹇鹃龉鹸麃麂鹀鼔齛鸿鼤齸鼨鹋鹉鸽鸻鼺 class齹龳龯鼤龮龭龬龩鼾鼺 #theme_wrappers 鸺鸸齸鼨齹鸵鸱鹰鼔鹋鹉鸽鸰鸮鼐鹘鹖龙龖鼔麞鼨鼄鸽齹

$element = [
  '#type' => 'my_element',
  '#config_one' => 'blue',
  '#theme_wrappers' => [
    'container' => [
      '#attributes' => [
        'class' => ['my-wrapper-class']
      ],
    ],
  ],
];

黮鸪鼔鼄鸽齛齘鸨鸧鹢齸鸣鹴
container.html.twig

{%
  set classes = [
    has_parent ? 'js-form-wrapper',
    has_parent ? 'form-wrapper',
  ]
%}
<div{{ attributes.addClass(classes) }}>{{ children }}</div>

探讨元素渲染数组流程

Drupal 7 鸞鸜鸛鸞鸗鸔鼔鹞鸿龮龭鹇鹃齹Drupal 8 鸐鸏鸌鸊齸鼨齕麎鸆鸂鷿鼔鸗鸔鷽鷻鷹鷶齹麘鷳齕鷰鹧鷬鷨麞鼨鷥鷤齕齸鼐鷣鷠鼈鹸麃鷟鷛鷚鼔麞鷘齛鸿齹Drupal 鷣鷠鷽鷻鷕鷒鹸麃麤麡鼔鷥鷤齹

Element Plugin / pre_render / Twig pattern 龔鹰鷍鷉齽

鷅鷂鷁齛鸿鶾麀鼔麖鶻鼐鶺鸜鶷 Drupal 8 鼔麞鶵齕鶲鶱鶭麋鶪鶨鶤龖齹鶢鸜鶟鼤黮鹢齛鸿齕鷰鹧鶜麤麡鹇鹃鶙鶖鼰鶒鸧齹鶐鶎麤麡鼔鹇鹃鶍鶋鹋鶊麏麞鼨鶒鸧鸨鸧鼈鶇鶄鶀 Drupal 8 黮鶒鸧龉鸰鼔鵾鵻鸊鵷鸿齹麤麡鹇鹃麏鵵鹧齦鵲齛齘麂鹀齐齎黪鹫齛鵱鹸麃 hook_preprocess_hook 黮黪鼹鼵齹鶻鷁鷰鹧鶺鸜鼯鹸麃鼹鼵鼔龶鵩齹

鶷鷣鷠鼔鵧鵥

齸鷘齛鸿鶷鷣鷠麂鵤鼔鵢鵞鼂鵜鼐鸂龬鷣鷠齔鹸麃鼯 template_preprocess_hook 齕齸鵙鵗鶷 #pre_render 鵕鵔齹鶻鼰鸗鸔鹸麃鼔麞齶鵐癖齕麡齶鷣鷠鶲鶱鹸麃鼯齸鵊鷘鹞鵈齹齸齶鵐癖鹽龶鵄鼾鵂鸛鵀鴽齕麎鴹鴷鼔鴴鴳鼐鵄鼺鼯鴯鷒鴬齕鶎鴫鴨鸛鴧麏鸂鼨鴣鹞齹

d8RecommendedRenderPath

评论 (写第一个评论)