Drupal:如何正确地将'class'数组添加到元素的'attributes'数组中?

时间:2017-08-28 00:45:22

标签: php arrays drupal drupal-7

我有一个构建菜单的模块。我想将css类添加到此模块生成的<a>标记中。

我已经使用dpm()找到了我需要添加类的正确数组。这是

['#localized_options']['attributes']

那里已经有一个[title]数组,但没有类的数组。

我尝试过几种不同的方式添加我的课程:

$item['#localized_options']['attributes']['class'] = "some-styles";

$item['#localized_options']['attributes']['class'][] = "some-styles";

$item['#localized_options']['attributes'] = array('class' => "some-styles");

但我一直收到错误:

  

致命错误:不能将字符串偏移用作数组

有人知道我应该怎么做吗?

1 个答案:

答案 0 :(得分:2)

根据Form api,属性应以#前缀开头。 所以我认为正确的方法是:

$item['#localized_options']['#attributes']['class'][] = 'some-styles';

参考: https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#attributes

PS:不要使用

$item['#localized_options']['#attributes'] = array('class' => "some-styles");

否则,您将完全删除#attributes只是为了添加您的CSS样式!这是错误的,因为许多其他模块可能会添加自己的#attributes属性!