Drupal 7 - add HTML inside #link form type entry?

我是研究僧i 提交于 2019-12-05 21:28:31

There's actually a much simpler way than custom-rolling a theme - just tell drupal_render() to treat '#title' as html.

function mymodule_save_progress_link($nid) {
  return array(
    '#type' => 'link',
    '#title' => '<span>unescaped HTML here</span> '.t('Save Progress'),
    '#href' => 'saveprogress/nojs/' . $nid,
    '#id' => 'saveprogress-link',
    '#ajax' => array(
      'wrapper' => 'level-form',
      'method' => 'html',
    ),
    '#options' => array(
      'html' => true,
    )
  );
}

This could be very handy for adding images or other elements to a click-able area.

I'm sure there's a better way, but here's one working method by using a custom theme. You need to register the custom theme function in hook_theme(), then disable and re-enable you module to update the theme registry. In your custom theme function, you can rewrite the output HTML, but you'll need to add a different class, 'use-ajax'.

/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array (
    'mymodule_link' => array(
      'render element' => 'element',
    ),
  );
}

/**
* Returns HTML for a mymodule link
*
* @param $variables
*   An associative array containing:
*   - element: A render element containing the properties of the link.
*
* @ingroup themeable
*/
function theme_mymodule_link($variables) {
  return l(
    '<span data-icon="&#61515;" '.
      'aria-hidden="true" class="mymodule-symbol"></span> '.
      $variables['element']['#title'],
    $variables['element']['#href'],
    array(
     'html' => TRUE, 
     'attributes' => array(
       'class' => array('use-ajax'), 
       'title' => $variables['element']['#title']
     )
    )
  );
}

Finally, require the form element to use this theme:

function mymodule_save_progress_link($nid) {
  return array(
    '#type' => 'link',
    '#title' => t('Save Progress'),
    '#href' => 'saveprogress/nojs/' . $nid,
    '#id' => 'saveprogress-link',
    '#ajax' => array(
      'wrapper' => 'level-form',
      'method' => 'html',
    ),
    '#theme' => 'mymodule_link',
  );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!