欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

How can I add a class to #markup output?


I'm using this code to add a cancel button to my form. The link is generated through #markup:

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );

I'd like to add a class, cancel, to the link. I tried adding this line:

'#attributes' => array('class' => array('cancel')),

but the class is not added. I'm guessing because #attributes cannot modify #markup? How can I add the class in this case?


I'm using this code to add a cancel button to my form. The link is generated through #markup:

  $form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination),
    '#weight' => 20,
  );

I'd like to add a class, cancel, to the link. I tried adding this line:

'#attributes' => array('class' => array('cancel')),

but the class is not added. I'm guessing because #attributes cannot modify #markup? How can I add the class in this case?

正确答案 


 

1down voteaccepted

You can do this...

$form['actions']['cancel'] = array(
    '#markup' => l(t('Cancel'), $destination, array('attributes' => array('class' => array('cancel')))),
    '#weight' => 20,
  );

The third argument on the 'link' function is for attributes and such...

l($text, $path, array $options = array())

Documentation: http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7

shareimprove this answer
 
   
This is great for that user's case, but would you know a way to make it more general on the form element itself, and not just the link generated? I'm asking because I have a similar issue, but would like to wrap the class around the entire element (#type => 'item') that's using #markup, but according to Drupal's FAPI page, #attributes isn't available for #item. – UnsettlingTrend Jul 15 '15 at 15:55
   
Have you tried using #prefix and #suffix? api.drupal.org/api/drupal/… – Alex Gill Jul 17 '15 at 10:00
   
Yeah, but I was trying to do it without having to add another div; I know, one more div is somewhat inconsequential, but I try to avoid the snowball effect...

来自  http://drupal.stackexchange.com/questions/54721/how-can-i-add-a-class-to-markup-output
普通分类: