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

评论 (写第一个评论)