drupal 8从标签模板访问输入类型

时间:2016-10-16 19:07:56

标签: drupal drupal-8

如何从表单元素标签模板(form-element-label.html.twig)中引用相应表单输入的输入类型?

1 个答案:

答案 0 :(得分:0)

该TWIG模板中没有元素类型。您将必须挂钩到form元素并将变量传递给元素标签钩。

/**
 * The contents of $variable['label'] will be passed to the preprocess
 * hook of the element's label.
 */
function theme_preprocess_form_element(array &$variables) {
  $variables['label']['#attributes']["data-element-type"] = $variables['element']['#type'];

}

/** 
 * Now we need to merge the array element we created in the previous hook
 * with the label's attributes.
 */
function theme_preprocess_form_element_label(array &$variables) {
  $variables['attributes'] = array_merge($variables['attributes'], $variables['element']['#attributes']);
}

标签将具有以下输出(我在电子邮件元素类型上进行测试)。

<label for="edit-email-addresses" data-element-type="email" class="js-form-required form-required">Email Addresses</label>

不要忘记清除缓存;)