现在后天添加的文章有一个link类型字段,需要在link字段的a标签上加一个class;后台无法设置,于是在mytheme.theme中使用template_preprocess_field()添加:
第一种写法只适合没有嵌套标签的字段。
function pfyhmhk_preprocess_field(&$variables){
if ($variables['element']['#bundle'] == 'white'){
if (!$variables['multiple']) {
$variables['attributes']['class'][] = 'shadow-button';
$variables['attributes']['data-attr'] = 'shadow-button';
}
foreach ($variables['items'] as $delta => &$item) {
$item['attributes']->setAttribute('class', 'shadow-button');
$item['attributes']->setAttribute('data-attr', 'shadow-button');
}
}
}
无嵌套:
有嵌套:
但是像link这种类型字段一般都是外层div,里面才是a标签,而一般我们是想将class加在a标签上的。所以就不能用上面的方法。
function pfyhmhk_preprocess_field(&$variables){
if ($variables['field_name'] == 'field_cta' && $variables['element']['#bundle'] == 'white') {
$variables['items'][0]['content']['#options']['attributes']['class'][] = 'shadow-button';
}
}
参考:https://drupal.stackexchange.com/questions/181341/add-class-to-content-field-link